or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-tool.mdglobal-registration.mdindex.mdinstance-creation.mdmodule-import.mdtransformation.md
tile.json

global-registration.mddocs/

0

# Global Registration and ESM Loader

1

2

Global ESM loader registration and native runtime mode for seamless TypeScript support across Node.js applications.

3

4

## Capabilities

5

6

### Global ESM Loader Registration

7

8

Register jiti as a global ESM loader to automatically handle TypeScript and JSX files across your entire Node.js application.

9

10

```typescript { .api }

11

// Import for automatic global registration

12

import "jiti/register";

13

```

14

15

**Usage Examples:**

16

17

```typescript

18

// Method 1: Import in your entry file

19

import "jiti/register";

20

import { config } from "./config.ts"; // Automatically works

21

22

console.log(config);

23

```

24

25

```bash

26

# Method 2: Use Node.js --import flag

27

node --import jiti/register index.js

28

29

# Method 3: Use via environment variable

30

NODE_OPTIONS="--import jiti/register" node index.js

31

```

32

33

**Requirements:**

34

- Node.js version 20 or higher (for global hooks support)

35

- ESM environment (type: "module" in package.json or .mjs files)

36

37

### Native Runtime Mode

38

39

Lightweight mode that uses runtime's native `import.meta.resolve` and dynamic `import()` capabilities without transformation.

40

41

```typescript { .api }

42

import { createJiti } from "jiti/native";

43

44

/**

45

* Creates a native jiti instance with limited API surface

46

* @param parentURL - Parent URL for resolution context

47

* @param jitiOptions - Limited options for native mode

48

* @returns Jiti instance with native-only capabilities

49

*/

50

function createJiti(parentURL?: string | URL, jitiOptions?: JitiOptions): NativeJiti;

51

52

interface NativeJiti {

53

// ✅ Supported methods

54

import<T>(id: string, opts?: JitiResolveOptions & { default?: true }): Promise<T>;

55

esmResolve(id: string, opts?: string | JitiResolveOptions): string;

56

57

// ❌ Unsupported methods (throw errors)

58

(id: string): never; // Throws: "jiti() is not supported in native mode, use jiti.import() instead"

59

transform(opts: TransformOptions): never; // Throws: "transform() is not supported in native mode"

60

evalModule(source: string, options?: EvalModuleOptions): never; // Throws: "evalModule() is not supported in native mode"

61

resolve: never; // Throws: "resolve() is not supported in native mode"

62

}

63

```

64

65

**Usage Examples:**

66

67

```typescript

68

import { createJiti } from "jiti/native";

69

70

// Create native jiti instance

71

const jiti = createJiti(import.meta.url);

72

73

// Only import() and esmResolve() work in native mode

74

const module = await jiti.import("./config.js");

75

const resolved = jiti.esmResolve("./utils.js");

76

77

// These methods throw errors in native mode:

78

try {

79

jiti.transform({ source: "code" }); // Throws: not supported in native mode

80

} catch (error) {

81

console.error(error.message); // "`transform()` is not supported in native mode"

82

}

83

84

try {

85

jiti.evalModule("code"); // Throws: not supported in native mode

86

} catch (error) {

87

console.error(error.message); // "`evalModule()` is not supported in native mode"

88

}

89

90

try {

91

jiti("./module"); // Throws: not supported in native mode

92

} catch (error) {

93

console.error(error.message); // "`jiti()` is not supported in native mode, use `jiti.import()` instead"

94

}

95

```

96

97

### ESM Loader Implementation

98

99

The global ESM loader provides automatic transformation for TypeScript and other supported file types through Node.js's module loading hooks.

100

101

**Supported File Types:**

102

- `.ts` - TypeScript files

103

- `.tsx` - TypeScript with JSX

104

- `.mts` - TypeScript ES modules

105

- `.cts` - TypeScript CommonJS modules

106

- `.js` - JavaScript (conditionally transformed)

107

- `.json` - JSON modules with proper ESM/CommonJS detection

108

109

**Loader Features:**

110

111

```typescript { .api }

112

// ESM Loader Hooks (internal implementation)

113

export async function resolve(specifier: string, context: ResolveContext, nextResolve: Function): Promise<ResolveResult>;

114

export async function load(url: string, context: LoadContext, nextLoad: Function): Promise<LoadResult>;

115

```

116

117

### Configuration via Environment Variables

118

119

Configure the global loader behavior using environment variables.

120

121

**Environment Variables:**

122

- `JITI_DEBUG` - Enable debug logging for loader operations

123

- `JITI_JSX` - Enable JSX transformation globally

124

- `JITI_FS_CACHE` - Control filesystem caching for loader

125

- `JITI_SOURCE_MAPS` - Enable source maps in loader transformations

126

- `JITI_MODULE_CACHE` - Control module caching for loader

127

- `JITI_INTEROP_DEFAULT` - Control default export interoperability

128

- `JITI_ALIAS` - Set module aliases (JSON string)

129

- `JITI_NATIVE_MODULES` - Native modules list (JSON string)

130

- `JITI_TRANSFORM_MODULES` - Modules to transform (JSON string)

131

- `JITI_TRY_NATIVE` - Try native import first

132

133

**Usage Examples:**

134

135

```bash

136

# Enable JSX and debug mode globally

137

JITI_JSX=1 JITI_DEBUG=1 node --import jiti/register app.js

138

139

# Disable caching for development

140

JITI_FS_CACHE=false node --import jiti/register dev-server.js

141

```

142

143

### Advanced Registration Patterns

144

145

**Conditional Registration:**

146

147

```typescript

148

// Only register in development

149

if (process.env.NODE_ENV === "development") {

150

await import("jiti/register");

151

}

152

153

// Import your TypeScript modules after registration

154

const { devUtils } = await import("./dev-utils.ts");

155

```

156

157

**Application-Wide TypeScript Support:**

158

159

```typescript

160

// main.ts - Entry point with global registration

161

import "jiti/register";

162

163

// Now all imports in your app automatically support TypeScript

164

import { config } from "./config/app.ts";

165

import { routes } from "./routes/index.ts";

166

import { middleware } from "./middleware/auth.ts";

167

168

async function startApp() {

169

const server = (await import("./server.ts")).default;

170

server.start();

171

}

172

173

startApp();

174

```

175

176

**Library Development:**

177

178

```typescript

179

// Enable TypeScript for your library's development

180

// lib/index.ts

181

export { LibraryClass } from "./core.ts";

182

export type { LibraryOptions } from "./types.ts";

183

184

// During development, use jiti for testing

185

// test/setup.ts

186

import "jiti/register";

187

import { test } from "./lib/index.ts"; // Uses TypeScript directly

188

```

189

190

### Native Mode Limitations and Benefits

191

192

**Benefits of Native Mode:**

193

- Extremely lightweight - no Babel dependencies

194

- Faster startup time

195

- Uses runtime's native capabilities

196

- Better compatibility with modern Node.js features

197

198

**Limitations:**

199

- No TypeScript transformation (only .js, .mjs, .cjs files)

200

- No JSX support

201

- No custom syntax transformations

202

- Limited error handling compared to full jiti

203

204

**When to Use Native Mode:**

205

206

```typescript

207

// ✅ Good for native mode - JavaScript only

208

const jiti = createJiti("jiti/native");

209

await jiti.import("./config.js");

210

await jiti.import("./utils.mjs");

211

212

// ❌ Not suitable for native mode - needs transformation

213

await jiti.import("./config.ts"); // TypeScript

214

await jiti.import("./component.tsx"); // JSX

215

```

216

217

### Integration with Build Tools

218

219

**Development vs Production:**

220

221

```typescript

222

// Development: Use global registration for TypeScript

223

if (process.env.NODE_ENV === "development") {

224

await import("jiti/register");

225

const { devConfig } = await import("./config.dev.ts");

226

} else {

227

// Production: Use compiled JavaScript

228

const { prodConfig } = await import("./config.prod.js");

229

}

230

```

231

232

**Testing Setup:**

233

234

```javascript

235

// vitest.config.js or jest.config.js

236

export default {

237

setupFilesAfterEnv: ["jiti/register"],

238

// Now test files can import TypeScript directly

239

};

240

```

241

242

**Development Scripts:**

243

244

```json

245

{

246

"scripts": {

247

"dev": "node --import jiti/register src/dev-server.ts",

248

"test": "NODE_OPTIONS='--import jiti/register' vitest",

249

"debug": "JITI_DEBUG=1 node --import jiti/register --inspect src/index.ts"

250

}

251

}

252

```

253

254

### Error Handling and Debugging

255

256

**Loader Error Handling:**

257

258

The ESM loader provides detailed error information for transformation failures:

259

260

```typescript

261

// If a TypeScript file has syntax errors, the loader will provide:

262

// - File location with line/column numbers

263

// - Syntax error details

264

// - Code frame showing the problematic code

265

266

try {

267

await import("./broken-syntax.ts");

268

} catch (error) {

269

console.error("TypeScript compilation failed:");

270

console.error(error.message);

271

console.error(error.location); // File:line:column

272

}

273

```

274

275

**Debug Mode:**

276

277

```bash

278

# Enable debug logging to see loader operations

279

JITI_DEBUG=1 node --import jiti/register app.ts

280

```

281

282

Output shows:

283

- File resolution details

284

- Transformation decisions

285

- Cache hit/miss information

286

- Performance timings

287

288

### Compatibility and Runtime Support

289

290

**Node.js Version Requirements:**

291

- Global registration: Node.js 20+ (requires module hooks)

292

- Native mode: Node.js 18+ (requires import.meta.resolve)

293

- Full jiti mode: Node.js 16+

294

295

**Runtime Detection:**

296

297

```typescript

298

// jiti automatically detects runtime capabilities

299

const jiti = createJiti(import.meta.url, {

300

tryNative: true // Try native import first, fallback to transformation

301

});

302

303

// In Bun, this automatically uses native capabilities

304

// In Node.js, this uses transformation when needed

305

const module = await jiti.import("./file.ts");

306

```

307

308

**Cross-Platform Support:**

309

310

```typescript

311

// Works across different JavaScript runtimes

312

import { createJiti } from "jiti/native";

313

314

// Deno support

315

const jiti = createJiti(import.meta.url);

316

const module = await jiti.import("./config.ts");

317

318

// Bun support with enhanced native capabilities

319

const jiti = createJiti(import.meta.url, {

320

tryNative: true // Bun has excellent native TypeScript support

321

});

322

```