TypeScript Require Extension for Node.js

0.3.0 · abandoned · verified Sun Apr 19

typescript-require is a Node.js `require` extension designed to enable direct loading of TypeScript (`.ts`) modules without a separate pre-compilation step. Upon initialization, it hooks into Node's module resolution, compiling `.ts` files on-the-fly when they are `require`d, resolving internal dependencies. Its current stable version is 0.3.0, released in 2012. Given its age and the evolution of the TypeScript ecosystem, it represents an early approach to running TypeScript directly in Node.js, predating more modern solutions like `ts-node` or native ESM support with `tsx`. Key differentiators at the time were its simplicity as a `require` hook and configurability for ES target and error handling, but it lacks support for modern TypeScript features or robust project configuration via `tsconfig.json`.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `typescript-require` with configuration options and then dynamically create and require a TypeScript module, showing its on-the-fly compilation capabilities.

/* app.js */
const path = require('path');
const fs = require('fs');

// Create a temporary directory for output if it doesn't exist
const tmpDir = path.join(__dirname, 'tmp');
if (!fs.existsSync(tmpDir)) {
    fs.mkdirSync(tmpDir);
}

// Initialize typescript-require with custom options
require('typescript-require')({
    targetES5: true,
    exitOnError: false, // Don't exit process immediately on error for demonstration
    tmpDir: tmpDir // Specify temporary directory
});

// Create a sample TypeScript file dynamically for demonstration
const tsContent = `
    export function lowercase(val: string): string {
        return val.toLowerCase();
    }

    export function uppercase(val: string): string {
        return val.toUpperCase();
    }
`;
const funcsPath = path.join(__dirname, 'funcs.ts');
fs.writeFileSync(funcsPath, tsContent);

// Require the TypeScript module
const funcs = require(funcsPath);

console.log(funcs.lowercase("HELLO FROM TYPESCRIPT!"));
console.log(funcs.uppercase("hello from typescript!"));

// Clean up generated files and directory
fs.unlinkSync(funcsPath);
// Optional: Clean up compiled JS files and source maps in tmpDir as well
fs.readdirSync(tmpDir).forEach(file => {
    if (file.startsWith('funcs.') && (file.endsWith('.js') || file.endsWith('.map'))) {
        fs.unlinkSync(path.join(tmpDir, file));
    }
});
fs.rmdirSync(tmpDir);

view raw JSON →