TypeScript Require Extension for Node.js
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
-
Error: Cannot find module 'some-ts-file'
cause The `typescript-require` hook was not initialized before attempting to require a `.ts` file, or the path is incorrect.fixEnsure `require('typescript-require');` is called once at the very beginning of your application's entry point, and verify the path to the `.ts` file. -
TypeError: Object has no method 'toLowerCase' (or similar runtime type errors)
cause TypeScript compilation errors occurred, potentially due to outdated `targetES5` settings or missing type definitions, leading to incorrect or incomplete JavaScript output that fails at runtime.fixCheck the `typescript-require` configuration options like `targetES5` and `nodeLib`. Review the TypeScript code for errors that might be silently emitted (if `emitOnError: true`) but still lead to broken JS. Consider enabling `exitOnError: true` temporarily to halt execution on compilation failures.
Warnings
- breaking This package is largely incompatible with modern TypeScript features, `tsconfig.json` project configuration, or ES Modules (ESM). It was designed for an older TypeScript compiler API and CommonJS environments. Attempting to use it with recent TypeScript syntax or module systems will lead to compilation errors or unexpected behavior.
- gotcha The `nodeLib` option is `false` by default, meaning `node.d.ts` definitions are not automatically loaded. This requires explicit `/// <reference path='node.d.ts'/>` comments in TypeScript files that use Node.js types, which is an outdated practice compared to modern `@types/node` imports.
- deprecated The `import ... module` syntax for internal module dependencies shown in the README (e.g., `import barmodule = module('barmodule');`) has been deprecated in modern TypeScript in favor of `import * as barmodule from './barmodule';` or default imports.
Install
-
npm install typescript-require -
yarn add typescript-require -
pnpm add typescript-require
Imports
- TypeScriptRequire
import 'typescript-require';
require('typescript-require'); - ConfiguredTypeScriptRequire
import typescriptRequire from 'typescript-require';
require('typescript-require')({ targetES5: true, exitOnError: false }); - TSModuleImport
import { myModule } from './myModule.ts';var myModule = require('./myModule.ts');
Quickstart
/* 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);