0
# CommonJS API
1
2
The CommonJS API (`tsx/cjs/api`) provides programmatic access to tsx's TypeScript transformation capabilities within CommonJS modules. It enables registration of tsx loaders and provides enhanced require functionality for TypeScript files.
3
4
## Capabilities
5
6
### Module Registration
7
8
Register tsx transformation hooks for CommonJS modules.
9
10
```javascript { .api }
11
/**
12
* Register tsx loader for CommonJS modules
13
* @param options - Optional configuration
14
* @returns Unregister function
15
*/
16
function register(options?: RegisterOptions): Unregister;
17
18
/**
19
* Register tsx loader with required namespace
20
* @param options - Configuration with required namespace
21
* @returns Namespaced unregister function with additional methods
22
*/
23
function register(options: RequiredProperty<RegisterOptions, 'namespace'>): NamespacedUnregister;
24
25
interface RegisterOptions {
26
namespace?: string;
27
}
28
29
type Unregister = () => void;
30
31
interface NamespacedUnregister extends Unregister {
32
require: ScopedRequire;
33
resolve: ScopedResolve;
34
unregister: Unregister;
35
}
36
37
type Register = {
38
(options: RequiredProperty<RegisterOptions, 'namespace'>): NamespacedUnregister;
39
(options?: RegisterOptions): Unregister;
40
};
41
```
42
43
**Usage Examples:**
44
45
```javascript
46
const { register } = require("tsx/cjs/api");
47
48
// Basic registration
49
const unregister = register();
50
51
// Now TypeScript files can be required
52
const myModule = require("./my-module.ts");
53
54
// Unregister when done
55
unregister();
56
57
// Namespaced registration for isolation
58
const api = register({ namespace: "my-app" });
59
const tsModule = api.require("./module.ts", __filename);
60
api.unregister();
61
```
62
63
### Enhanced Require
64
65
Require TypeScript files directly with full transformation support.
66
67
```javascript { .api }
68
/**
69
* Require TypeScript files with transformation
70
* @param id - Module identifier or path
71
* @param fromFile - Current file path (__filename or import.meta.url)
72
* @returns Module exports
73
*/
74
function require(id: string, fromFile: string | URL): any;
75
```
76
77
**Usage Examples:**
78
79
```javascript
80
const { require: tsxRequire } = require("tsx/cjs/api");
81
82
// Require TypeScript files
83
const utils = tsxRequire("./utils.ts", __filename);
84
const config = tsxRequire("./config.ts", __filename);
85
86
// Works with npm packages written in TypeScript
87
const myPackage = tsxRequire("my-typescript-package", __filename);
88
89
// Relative path resolution
90
const helper = tsxRequire("../helpers/format.ts", __filename);
91
```
92
93
### Scoped Operations
94
95
When using namespace registration, access to scoped require and resolve functions.
96
97
```javascript { .api }
98
type ScopedRequire = (
99
id: string,
100
fromFile: string | URL,
101
) => any;
102
103
type ScopedResolve = (
104
id: string,
105
fromFile: string | URL,
106
resolveOptions?: { paths?: string[] | undefined },
107
) => string;
108
```
109
110
**Usage Examples:**
111
112
```javascript
113
const { register } = require("tsx/cjs/api");
114
115
// Create namespaced registration
116
const api = register({ namespace: "isolated-context" });
117
118
// Use scoped require - isolated from other tsx instances
119
const module1 = api.require("./module1.ts", __filename);
120
const module2 = api.require("./module2.ts", __filename);
121
122
// Use scoped resolve to get file paths
123
const resolvedPath = api.resolve("./module.ts", __filename);
124
console.log(resolvedPath); // Full resolved path
125
126
// Cleanup
127
api.unregister();
128
```
129
130
### Module Resolution
131
132
tsx enhances Node.js module resolution to handle TypeScript files and extensions.
133
134
**Features:**
135
- Resolves `.ts`, `.tsx`, `.mts`, `.cts` extensions
136
- Handles both relative and absolute imports
137
- Preserves query parameters in module paths
138
- Supports namespace isolation for multiple tsx instances
139
140
**Usage Examples:**
141
142
```javascript
143
const { register } = require("tsx/cjs/api");
144
145
register();
146
147
// These all work after registration
148
require("./config.ts"); // TypeScript file
149
require("./component.tsx"); // TSX file
150
require("./module.mts"); // ES module TypeScript
151
require("./legacy.cts"); // CommonJS TypeScript
152
153
// Query parameters are preserved
154
require("./module.ts?version=1");
155
```
156
157
### Integration Patterns
158
159
Common patterns for integrating tsx in CommonJS applications.
160
161
**Temporary Registration:**
162
163
```javascript
164
const { register } = require("tsx/cjs/api");
165
166
function loadTypeScriptConfig() {
167
const unregister = register();
168
try {
169
return require("./config.ts");
170
} finally {
171
unregister();
172
}
173
}
174
```
175
176
**Application-wide Setup:**
177
178
```javascript
179
// app.js entry point
180
const { register } = require("tsx/cjs/api");
181
182
// Register once at application startup
183
register();
184
185
// Now entire application can require TypeScript
186
const server = require("./src/server.ts");
187
const routes = require("./src/routes.ts");
188
const middleware = require("./src/middleware.ts");
189
190
server.start();
191
```
192
193
**Multiple Isolated Contexts:**
194
195
```javascript
196
const { register } = require("tsx/cjs/api");
197
198
// Create separate contexts for different purposes
199
const appContext = register({ namespace: "app" });
200
const testContext = register({ namespace: "test" });
201
202
// Load app modules
203
const appModule = appContext.require("./app.ts", __filename);
204
205
// Load test modules (isolated from app)
206
const testModule = testContext.require("./test.ts", __filename);
207
208
// Cleanup both contexts
209
appContext.unregister();
210
testContext.unregister();
211
```
212
213
## Types
214
215
### Core Types
216
217
```javascript { .api }
218
// Available through require("tsx/cjs/api")
219
220
interface LoaderState {
221
enabled: boolean;
222
}
223
224
type ResolveFilename = typeof Module._resolveFilename;
225
type SimpleResolve = (request: string) => string;
226
```
227
228
### Error Handling
229
230
tsx integrates with Node.js error handling and preserves stack traces for TypeScript files.
231
232
#### TypeScript Transformation Errors
233
234
```javascript
235
const { register } = require("tsx/cjs/api");
236
237
register();
238
239
try {
240
const module = require("./broken.ts");
241
} catch (error) {
242
// Error includes TypeScript source locations with source maps
243
console.error('TypeScript compilation error:', error.stack);
244
245
// Handle specific error types
246
if (error.code === 'MODULE_NOT_FOUND') {
247
console.error('Module could not be resolved:', error.path);
248
}
249
}
250
```
251
252
#### Registration Errors
253
254
```javascript
255
const { register } = require("tsx/cjs/api");
256
257
try {
258
const unregister = register();
259
// Registration successful
260
} catch (error) {
261
console.error('Failed to register tsx loader:', error.message);
262
throw error;
263
}
264
```
265
266
#### Scoped Require Errors
267
268
```javascript
269
const { register } = require("tsx/cjs/api");
270
271
const api = register({ namespace: "my-app" });
272
273
try {
274
const module = api.require("./missing-file.ts", __filename);
275
} catch (error) {
276
if (error.code === 'MODULE_NOT_FOUND') {
277
console.error('TypeScript module not found:', error.path);
278
} else {
279
console.error('Error loading TypeScript module:', error.stack);
280
}
281
}
282
283
api.unregister();
284
```
285
286
#### Module Resolution Errors
287
288
```javascript
289
const { register } = require("tsx/cjs/api");
290
291
register();
292
293
try {
294
// Invalid module path
295
const module = require("./non-existent-path/module.ts");
296
} catch (error) {
297
if (error.code === 'MODULE_NOT_FOUND') {
298
console.error('Cannot resolve module:', error.message);
299
console.error('Attempted paths:', error.requireStack);
300
}
301
}
302
```