tsx.require()
Synchronously load TypeScript through an enhanced CommonJS require() function without enabling tsx for unrelated loads. This fits tools that must load user files synchronously.
Install tsx and check compatibility. This API uses the CommonJS loading path; see scope and lifetime for shared limitations and module formats for execution and export interoperability.
Arguments and return values
Import require from tsx/cjs/api, or access it through require('tsx/cjs/api') in CommonJS.
| Function | Arguments | Return value |
|---|---|---|
tsx.require(id, fromFile) | Required id: string, required fromFile: string | URL | Module exports, synchronously |
tsx.require.resolve(id, fromFile, options?) | Same required arguments; optional options: { paths?: string[] } | Resolved cache key as a string, without evaluating the module |
fromFile is the importing file's absolute path, file URL string, or URL. Pass __filename from CommonJS or import.meta.url from ESM. Relative requests resolve from that file, not the working directory. Bare package requests do not use fromFile to establish a package search context. options.paths is omitted by default and supplies Node.js's optional package search paths.
Use the CommonJS entry for the resolver examples below. The named export in config.cts is available as .port on the returned exports.
ESM resolver limitation
Calling .resolve() through the ESM-imported API currently throws ReferenceError: module is not defined. Use the CommonJS require('tsx/cjs/api') entry when resolution is needed. This temporary workaround is tracked in issue #865.
The exported function also exposes these CommonJS properties:
| Property | Type | Meaning |
|---|---|---|
.cache | Object mapping cache keys to Node.js module objects | Shared CommonJS module cache |
.extensions | Object mapping extensions to loader functions | Shared CommonJS extension handlers |
.main | Node.js module object or undefined | The underlying require function's main-module value |
.resolve.paths(request) | Required request: string; returns string[] | null | Underlying require function's package lookup paths, or null for a built-in |
These properties have Node.js's underlying values rather than separate per-call copies. They are not loading options.
Usage
Create this file in a project with tsx installed:
config.cts
export const port: number = 3000CommonJS
Create this file beside it:
load.cjs
const tsx = require('tsx/cjs/api')
const loaded = tsx.require('./config.cts', __filename)
const resolvedPath = tsx.require.resolve('./config.cts', __filename)
console.log(loaded.port)
console.log(resolvedPath)Run from that project directory:
node ./load.cjsExpected output excerpt, with project-dependent path and namespace:
3000
/…/config.cts?namespace=…ESM
Create this file beside the same config.cts:
load.mjs
import { require as tsxRequire } from 'tsx/cjs/api'
const loaded = tsxRequire('./config.cts', import.meta.url)
console.log(loaded.port)node ./load.mjsIt prints:
3000Caching and lifetime
The API lazily creates a namespace and reuses it for subsequent calls. Requiring the same resolved file again returns its cached exports. Use the CommonJS entry's tsx.require.resolve() to obtain the exact namespaced cache key rather than constructing one yourself.
There is no unregister method on tsx.require(). Its scoped registration remains available for later calls from loaded code. Use scoped CommonJS registration if you need a separate namespace and explicit cleanup.
Configuration
There are no per-call tsconfig or onImport options. Configuration uses normal tsconfig lookup, including the optional string environment variable TSX_TSCONFIG_PATH. When unset, lookup uses the working directory; relative custom paths also use that directory.
Tracking loaded files
CommonJS cache entries expose a module's children. After the existing statements in load.cjs, add this fragment to collect the currently recorded CommonJS dependency graph:
const visited = new Set()
const files = new Set()
const collectDependencies = (loadedModule) => {
if (!loadedModule || visited.has(loadedModule)) {
return
}
visited.add(loadedModule)
files.add(loadedModule.filename)
for (const child of loadedModule.children) {
collectDependencies(child)
}
}
collectDependencies(tsx.require.cache[resolvedPath])
console.log([...files])Run node ./load.cjs. After the original output, the added statement prints an array containing the configuration module's namespaced filename. Expected additional output excerpt:
[ '/…/config.cts?namespace=…' ]The visited set prevents infinite recursion for circular dependencies. This is a snapshot of cached CommonJS dependencies, not all ESM imports or files the code reads. Collect again after later loads if needed.
Deleting tsx.require.cache[resolvedPath] causes the next load of that module to evaluate it again, but does not automatically invalidate its children.
