### Install tsx globally Source: https://github.com/privatenumber/tsx/blob/master/docs/getting-started.md Install tsx globally to use it from any directory on your system. ```sh $ npm install -g tsx ``` ```sh $ pnpm add -g tsx ``` ```sh Yarn 2 doesn't support global installation https://yarnpkg.com/migration/guide#use-yarn-dlx-instead-of-yarn-global ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/privatenumber/tsx/blob/master/CONTRIBUTING.md Install project dependencies using pnpm after cloning the repository. Ensure Node.js version is set using nvm if necessary. ```bash nvm i # Install or use Node.js version pnpm i # Install dependencies ``` -------------------------------- ### Install TypeScript and Node Types Source: https://github.com/privatenumber/tsx/blob/master/docs/typescript.md Install TypeScript and Node.js API types as development dependencies using npm, pnpm, or yarn. ```sh $ npm install -D typescript @types/node ``` ```sh $ pnpm add -D typescript @types/node ``` ```sh $ yarn add -D typescript @types/node ``` -------------------------------- ### Run a TypeScript file with npx Source: https://github.com/privatenumber/tsx/blob/master/docs/getting-started.md Execute a TypeScript file directly using npx without prior installation. ```sh npx tsx ./script.ts ``` -------------------------------- ### Basic package entry point in package.json Source: https://github.com/privatenumber/tsx/blob/master/docs/compilation.md Configure the main entry point for your package using the 'exports' field in package.json. This example sets the ESM entry point. ```json { "exports": "./dist/index.mjs" } ``` -------------------------------- ### Project Scripts with pnpm Source: https://github.com/privatenumber/tsx/blob/master/docs/shell-scripts.md Use this hashbang when tsx is installed locally in your project and you are using pnpm to manage dependencies. ```typescript #!/usr/bin/env -S pnpm tsx console.log('argv:', process.argv.slice(2)) ``` -------------------------------- ### Start TypeScript REPL with tsx Source: https://github.com/privatenumber/tsx/blob/master/docs/node-enhancement.md Initiate an interactive TypeScript REPL session by running the 'tsx' command. This provides an enhanced Node.js REPL with TypeScript support. ```sh tsx ``` -------------------------------- ### Run a TypeScript file globally Source: https://github.com/privatenumber/tsx/blob/master/docs/getting-started.md Execute a TypeScript file directly using the globally installed tsx command. ```sh tsx file.ts ``` -------------------------------- ### Project Scripts with npm Source: https://github.com/privatenumber/tsx/blob/master/docs/shell-scripts.md Use this hashbang when tsx is installed locally in your project and you are using npm to manage dependencies. ```typescript #!/usr/bin/env -S npx tsx console.log('argv:', process.argv.slice(2)) ``` -------------------------------- ### Global Scripts Source: https://github.com/privatenumber/tsx/blob/master/docs/shell-scripts.md If tsx is installed globally, reference 'tsx' directly in the hashbang for your script. ```typescript #!/usr/bin/env tsx console.log('argv:', process.argv.slice(2)) ``` -------------------------------- ### Pre-commit Hook for Type Checking Source: https://github.com/privatenumber/tsx/blob/master/docs/typescript.md Configure a pre-commit hook using simple-git-hooks to automatically run type checks before each commit. This example shows how to register hooks and specify the type-check script. ```js // package.json { // ... "scripts": { // Register Git hooks on `npm install` "prepare": "simple-git-hooks"// [!code ++] }, "simple-git-hooks": { "pre-commit": "npm run type-check",// [!code ++] // Or if you have multiple commands "pre-commit": [ "npm run lint", "npm run type-check"// [!code ++] ] } } ``` -------------------------------- ### Project Scripts with yarn Source: https://github.com/privatenumber/tsx/blob/master/docs/shell-scripts.md Use this hashbang when tsx is installed locally in your project and you are using yarn to manage dependencies. ```typescript #!/usr/bin/env -S yarn tsx console.log('argv:', process.argv.slice(2)) ``` -------------------------------- ### Install tsx as a development dependency Source: https://github.com/privatenumber/tsx/blob/master/docs/getting-started.md Add tsx to your project's development dependencies using npm, pnpm, or yarn. ```sh $ npm install -D tsx ``` ```sh $ pnpm add -D tsx ``` ```sh $ yarn add -D tsx ``` -------------------------------- ### Run tsx with Inspect Flag Source: https://github.com/privatenumber/tsx/blob/master/docs/vscode.md Start your tsx application with the --inspect-brk flag to enable debugging. This command allows VS Code to attach to the running process. ```sh tsx --inspect-brk ./your-file.ts ``` -------------------------------- ### Invoke tsx within a project Source: https://github.com/privatenumber/tsx/blob/master/docs/getting-started.md Run tsx for a specific file using your package manager after installing it as a project dependency. ```sh $ npx tsx ./file.ts ``` ```sh $ pnpm tsx ./file.ts ``` ```sh $ yarn tsx ./file.ts ``` -------------------------------- ### Run tsx in Watch Mode Source: https://github.com/privatenumber/tsx/blob/master/docs/watch-mode.md Use this command to start tsx in watch mode. It will automatically re-run your script when any of its dependencies change. ```bash tsx watch ./file.ts ``` -------------------------------- ### Track Loaded Files with `tsx.require.cache` Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/tsx-require.md Leverage `tsx.require.cache` to track loaded modules, which is useful for dependency tracking or implementing watchers. This example shows how to recursively collect all dependent files. ```javascript const resolvedPath = tsx.require.resolve('./file', import.meta.url) const collectDependencies = module => [ module.filename, ...module.children.flatMap(collectDependencies) ] console.log(collectDependencies(tsx.require.cache[resolvedPath])) // ['/file.ts', '/foo.ts', '/bar.ts'] ``` -------------------------------- ### VS Code Debug Configuration: Run tsx Source: https://github.com/privatenumber/tsx/blob/master/docs/vscode.md Configure VS Code to launch and debug the currently open TypeScript/JavaScript file using tsx. Ensure tsx is installed locally. ```json { "name": "tsx", "type": "node", "request": "launch", // Debug current file in VSCode "program": "${file}", /* * Path to tsx binary * Assuming locally installed */ "runtimeExecutable": "tsx", /* * Open terminal when debugging starts (Optional) * Useful to see console.logs */ "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", // Files to exclude from debugger (e.g. call stack) "skipFiles": [ // Node.js internal core modules "/**", // Ignore all dependencies (optional) "${workspaceFolder}/node_modules/**", ], } ``` -------------------------------- ### CJS Export Annotation for Node.js Preparser Source: https://github.com/privatenumber/tsx/blob/master/notes/node/cjs-esm-interop.md This is an example of esbuild's dead-code CJS export annotation. It is used by tsx to signal to Node.js's CommonJS lexer that named exports are available, even though this specific line of code never executes. ```javascript 0 && (module.exports = { namedExport }); ``` -------------------------------- ### VS Code Debug Configuration: Attach to Process Source: https://github.com/privatenumber/tsx/blob/master/docs/vscode.md Configure VS Code to attach the debugger to a running Node.js process. This is useful for debugging tsx applications that are started separately. ```json { "name": "Attach to process", "type": "node", "request": "attach", "port": 9229, "skipFiles": [ // Node.js internal core modules "/**", // Ignore all dependencies (optional) "${workspaceFolder}/node_modules/**", ], } ``` -------------------------------- ### CLI entry point in package.json Source: https://github.com/privatenumber/tsx/blob/master/docs/compilation.md Specify the command-line interface entry point for your package using the 'bin' field in package.json. ```json { "bin": "./dist/cli.mjs" } ``` -------------------------------- ### VS Code launch.json - Initial Configuration Source: https://github.com/privatenumber/tsx/blob/master/docs/vscode.md This is the base structure for a VS Code launch configuration file. Add specific debugging configurations to the 'configurations' array. ```json { "version": "0.2.0", "configurations": [ /* * Each config in this array corresponds to an option * in the debug drop-down */ ] } ``` -------------------------------- ### Run Script with Arguments Source: https://github.com/privatenumber/tsx/blob/master/docs/shell-scripts.md Execute the script directly and pass arguments to it. ```shell ./file.ts hello world ``` -------------------------------- ### Local Manual Testing Source: https://github.com/privatenumber/tsx/blob/master/CONTRIBUTING.md Run the compiled CLI tool locally using its absolute path. This is useful for manual testing of changes. ```bash /tsx/dist/cli.mjs ``` -------------------------------- ### Build package using pkgroll (yarn) Source: https://github.com/privatenumber/tsx/blob/master/docs/compilation.md Execute the pkgroll command via yarn to compile your project's TypeScript files into JavaScript, assuming your package.json is configured correctly. ```sh $ yarn pkgroll ``` -------------------------------- ### Run Benchmark Scenarios Source: https://github.com/privatenumber/tsx/blob/master/scripts/benchmark/README.md Execute benchmark tests for different tsx scenarios. Use positional arguments to select specific scenarios or run the default set. Flags can modify Node version, module count, and output format. ```sh pnpm benchmark # all scenarios, current Node, 1000 modules ``` ```sh pnpm benchmark esm-ts --compare 4.21.0 # one scenario vs a released version ``` ```sh pnpm benchmark hooks-passthrough --node 24.10.0 # async (worker) vs sync hooks (see below) ``` ```sh pnpm benchmark esm-ts --scale # per-module cost + fixed startup tax ``` ```sh pnpm --silent benchmark --json > results.json # raw per-run data ``` -------------------------------- ### Build package using pkgroll (npm) Source: https://github.com/privatenumber/tsx/blob/master/docs/compilation.md Execute the pkgroll command via npx to compile your project's TypeScript files into JavaScript, assuming your package.json is configured correctly. ```sh $ npx pkgroll ``` -------------------------------- ### Tracking Loaded Files with onImport Hook Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/ts-import.md Illustrates how to use the `onImport` hook with `tsImport()` to detect and log files as they are loaded. ```APIDOC ## Tracking loaded files Detect files that get loaded with the `onImport` hook: ```ts tsImport('./file.ts', { parentURL: import.meta.url, onImport: (file: string) => { console.log(file) // file:///foo.ts } }) ``` ``` -------------------------------- ### Tracking Loaded Files with tsx.require.cache Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/tsx-require.md Illustrates how to track loaded files using `tsx.require.cache`. This is useful for dependency tracking, especially when implementing a file watcher. ```APIDOC ## Tracking Loaded Files ### Description The CommonJS API tracks loaded modules in `require.cache`. This can be leveraged for dependency tracking, which is particularly useful when implementing a watcher. ### Example ```js const tsx = require('tsx/cjs/api') // Resolve the path of the file const resolvedPath = tsx.require.resolve('./file', import.meta.url) // Recursively collect all dependencies of a module const collectDependencies = module => [ module.filename, ...module.children.flatMap(collectDependencies) ] // Log the dependencies of the resolved file console.log(collectDependencies(tsx.require.cache[resolvedPath])) // Expected output: ['/file.ts', '/foo.ts', '/bar.ts'] ``` ``` -------------------------------- ### Dual package entry points (CJS & ESM) in package.json Source: https://github.com/privatenumber/tsx/blob/master/docs/compilation.md Define both CommonJS and ESM entry points, along with their corresponding type definitions, in the 'exports' field of package.json for broader compatibility. ```json { "main": "./dist/index.cjs", "module": "./dist/index.mjs", "types": "./dist/index.d.cts", "exports": { "require": { "types": "./dist/index.d.cts", "default": "./dist/index.cjs" }, "import": { "types": "./dist/index.d.mts", "default": "./dist/index.mjs" } } } ``` -------------------------------- ### Make Script Executable Source: https://github.com/privatenumber/tsx/blob/master/docs/shell-scripts.md After writing your script, use chmod to make it executable. ```shell chmod +x ./file.ts ``` -------------------------------- ### Recommended tsconfig.json Configuration Source: https://github.com/privatenumber/tsx/blob/master/docs/typescript.md A recommended tsconfig.json configuration for consistent type-checking behavior, including module detection and JSON module resolution. ```jsonc { "compilerOptions": { "moduleDetection": "force", "module": "Preserve", "resolveJsonModule": true, "allowJs": true, "esModuleInterop": true, "isolatedModules": true, } } ``` -------------------------------- ### Verify Node.js Version Boundaries Source: https://github.com/privatenumber/tsx/blob/master/notes/node/README.md This script helps identify the first release tag per major Node.js line that contains a specific commit. It's used to pinpoint version boundaries for verifying Node.js behavior changes. ```bash cd /path/to/nodejs/node git fetch --tags # Every commit carrying a PR-URL trailer = main-line commit + all backport # cherry-picks. Collect all release tags containing them, first per major line: pr=59929 { for sha in $(git log --grep "PR-URL: https://github.com/nodejs/node/pull/${pr}\" --format=%H --all); do git tag --contains "$sha" | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' done; } | sort -u -V | awk -F. '{maj=$1} maj!=prev{print; prev=maj}' ``` -------------------------------- ### Add build script to package.json Source: https://github.com/privatenumber/tsx/blob/master/docs/compilation.md Conveniently add a 'build' script to your package.json that runs 'pkgroll', allowing you to compile your project with a simple 'npm run build' command. ```json { // Optional: build script "scripts": { "build": "pkgroll" } } ``` -------------------------------- ### Run Automated Tests Source: https://github.com/privatenumber/tsx/blob/master/CONTRIBUTING.md Execute the project's automated tests. The `CI=1` prefix is used to run tests in a manner consistent with continuous integration environments. ```bash pnpm test # Regular test CI=1 pnpm test # CI environments ``` -------------------------------- ### Run TypeScript with Node.js CLI Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/node-cli.md Use the `--import` flag with `node` to run TypeScript files directly. This is the recommended approach for modern Node.js versions. ```sh node --import tsx ./file.ts ``` -------------------------------- ### Build package using pkgroll (pnpm) Source: https://github.com/privatenumber/tsx/blob/master/docs/compilation.md Execute the pkgroll command via pnpm to compile your project's TypeScript files into JavaScript, assuming your package.json is configured correctly. ```sh $ pnpm pkgroll ``` -------------------------------- ### Use NODE_OPTIONS for TSX Import Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/node-cli.md When direct access to the `node` command is unavailable, use the `NODE_OPTIONS` environment variable to pass the `--import tsx` flag to `npx` or other binaries. ```sh NODE_OPTIONS='--import tsx' npx some-binary ``` -------------------------------- ### Build tsx Project Source: https://github.com/privatenumber/tsx/blob/master/CONTRIBUTING.md Compile the source code into the `dist` directory. For easier debugging, minification can be temporarily disabled by modifying the `build` script in `package.json`. ```bash pnpm build # Compiles to `dist` ``` -------------------------------- ### Run TypeScript with Node.js CLI (Deprecated Loader) Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/node-cli.md For Node.js versions 20.5.1 and below, use the deprecated `--loader` flag instead of `--import`. ```sh node --loader tsx ./file.ts ``` -------------------------------- ### Import TypeScript with ESM Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/ts-import.md Use `tsImport` from `tsx/esm/api` for dynamic imports in ESM. Pass the file path and `import.meta.url` for context. Repeated calls to `tsImport` for the same file will re-load the module. ```js import { tsImport } from 'tsx/esm/api' const loaded = await tsImport('./file.ts', import.meta.url) // If tsImport is used to load file.ts again, // it does not yield a cache-hit and re-loads it const loadedAgain = await tsImport('./file.ts', import.meta.url) ``` -------------------------------- ### tsx.require() Usage Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/tsx-require.md Demonstrates how to use tsx.require() and tsx.require.resolve() in both CommonJS and ESM environments. The second argument, representing the current file path, is crucial for resolving the import context. ```APIDOC ## tsx.require() and tsx.require.resolve() ### Description Use `tsx.require()` to import TypeScript files in CommonJS mode and `tsx.require.resolve()` to get the resolved path of a module. The current file path must be passed as the second argument. ### CommonJS Usage ```js const tsx = require('tsx/cjs/api') // Import a TypeScript file const tsLoaded = tsx.require('./file.ts', __filename) // Get the resolved path of a module const tsFilepath = tsx.require.resolve('./file.ts', __filename) ``` ### ESM Usage ```js import { require } from 'tsx/cjs/api' // Import a TypeScript file const tsLoaded = require('./file.ts', import.meta.url) // Get the resolved path of a module const tsFilepath = require.resolve('./file.ts', import.meta.url) ``` ### Caveats - `import()` calls within loaded files are not enhanced. Use `tsImport()` instead. - Top-level await is not supported due to ESM to CommonJS compilation. ``` -------------------------------- ### Include Specific Files/Directories in Watch Mode Source: https://github.com/privatenumber/tsx/blob/master/docs/watch-mode.md Use the --include flag to specify additional files or directories that tsx should watch. This is useful for non-TS dependencies like configuration files or data files. ```bash tsx watch --include ./other-dep.txt --include "./other-deps/*" ./file.ts ``` -------------------------------- ### Flag and Argument Positioning with tsx Source: https://github.com/privatenumber/tsx/blob/master/docs/node-enhancement.md Ensure correct placement of tsx flags and script arguments. tsx flags should follow 'tsx', while script-specific flags and arguments come after the script path. ```sh tsx [tsx flags] ./file.ts [flags & arguments for file.ts] ``` -------------------------------- ### Lint and Type-Check Code Source: https://github.com/privatenumber/tsx/blob/master/CONTRIBUTING.md Ensure code quality by running ESLint for linting and TypeScript for type checking. These commands help maintain code standards and catch potential type errors. ```bash pnpm lint # ESLint pnpm type-check # TypeScript type checking ``` -------------------------------- ### tsImport() with Custom tsconfig.json Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/ts-import.md Shows how to specify a custom tsconfig.json path or disable tsconfig lookup when using tsImport(). ```APIDOC ## Custom `tsconfig.json` path ```ts tsImport('./file.ts', { parentURL: import.meta.url, tsconfig: './custom-tsconfig.json' }) ``` ## Disable `tsconfig.json` lookup ```ts tsImport('./file.ts', { parentURL: import.meta.url, tsconfig: false }) ``` ``` -------------------------------- ### Specify Custom tsconfig.json Path Source: https://github.com/privatenumber/tsx/blob/master/docs/typescript.md Use the --tsconfig flag with tsx to specify a tsconfig.json file from a custom path. ```sh tsx --tsconfig ./path/to/tsconfig.custom.json ./file.ts ``` -------------------------------- ### Recommended tsconfig.json for Node.js Type Stripping Source: https://github.com/privatenumber/tsx/blob/master/notes/node/type-stripping.md This configuration is recommended for Node.js projects using TypeScript 5.8+ to match Node's runtime behavior regarding type stripping and module syntax. ```json { "compilerOptions": { "noEmit": true, "target": "esnext", "module": "nodenext", "rewriteRelativeImportExtensions": true, "erasableSyntaxOnly": true, "verbatimModuleSyntax": true } } ``` -------------------------------- ### Import tsx for ESM Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/entry-point.md Import 'tsx' at the top of your entry-file to enable TS file loading via dynamic imports. This enhancement is only effective for dynamic imports made after registration due to ESM's static import evaluation order. ```js import 'tsx' // Now you can load TS files await import('./file.ts') ``` -------------------------------- ### Import tsx/esm for Module Mode Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/entry-point.md Import 'tsx/esm' at the top of your entry-file when using module mode to enable loading TS files. This is specifically for ESM environments and uses dynamic imports. ```js import 'tsx/esm' // Now you can load TS files await import('./file.ts') ``` -------------------------------- ### Run Node.js Test Runner with tsx Source: https://github.com/privatenumber/tsx/blob/master/docs/node-enhancement.md Execute the Node.js built-in test runner with TypeScript support by using the 'tsx --test' command. It automatically detects TypeScript test files. ```sh tsx --test ``` -------------------------------- ### Import TypeScript with CommonJS Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/ts-import.md Use `tsImport` from `tsx/esm/api` for dynamic imports in CommonJS. Pass the file path and `__filename` for context. ```js const { tsImport } = require('tsx/esm/api') const loaded = await tsImport('./file.ts', __filename) ``` -------------------------------- ### Compare Node Version Behavior Source: https://github.com/privatenumber/tsx/blob/master/scripts/benchmark/README.md Compare tsx behavior between async worker threads (older Node versions) and sync in-thread hooks (newer Node versions). This command specifically targets the 'hooks-passthrough' scenario. ```sh pnpm benchmark hooks-passthrough --node 24.10.0 # 24.10.0 = async worker, current (>=24.11.1) = sync ``` -------------------------------- ### Specify Custom tsconfig.json Path Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/ts-import.md Provide a custom path to a `tsconfig.json` file using the `tsconfig` option within the options object passed to `tsImport`. ```ts tsImport('./file.ts', { parentURL: import.meta.url, tsconfig: './custom-tsconfig.json' }) ``` -------------------------------- ### Execute Node.js Script with tsx Source: https://github.com/privatenumber/tsx/blob/master/docs/index.md You can pass Node.js CLI flags and JavaScript files to tsx, just as you would with the `node` command. This allows for flexible execution with various options. ```bash tsx --env-file=.env ./file.js ``` -------------------------------- ### Track Loaded Files with onImport Hook Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/register-esm.md Utilize the `onImport` hook during registration to track files as they are loaded. This is particularly useful for implementing watchers or dependency tracking. ```typescript register({ onImport: (file: string) => { console.log(file) // 'file:///foo.ts' } }) ``` -------------------------------- ### Tracking Loaded Files with onImport Hook Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/register-esm.md Allows tracking of files loaded by the TSX enhancement using the `onImport` hook. ```APIDOC ## Tracking Loaded Files ### Description Provides an `onImport` hook that is called whenever a file is loaded by the TSX enhancement. This is useful for tracking dependencies, especially when setting up watchers. ### Usage ```ts import { register } from 'tsx/esm/api' register({ onImport: (file: string) => { console.log(file) // Example: 'file:///foo.ts' } }) ``` ### Parameters - `onImport` (function): A callback function that receives the path of the loaded file as a string argument. ``` -------------------------------- ### Swap Node.js for tsx Source: https://github.com/privatenumber/tsx/blob/master/docs/node-enhancement.md Replace 'node' with 'tsx' to run JavaScript and TypeScript files. This command supports all standard Node.js command-line flags. ```sh node --no-warnings --env-file=.env ./file.js ``` ```sh tsx --no-warnings --env-file=.env ./file.js ``` -------------------------------- ### Track Loaded Files with onImport Hook Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/ts-import.md Use the `onImport` hook to detect and log files loaded by `tsImport`. The hook receives the file path as an argument. ```ts tsImport('./file.ts', { parentURL: import.meta.url, onImport: (file: string) => { console.log(file) // file:///foo.ts } }) ``` -------------------------------- ### Use tsx in package.json scripts Source: https://github.com/privatenumber/tsx/blob/master/docs/getting-started.md Reference tsx directly in your package.json scripts for convenient execution. ```js // package.json { "scripts": { "start": "tsx ./file.ts"// [!code highlight] } } ``` -------------------------------- ### Import TypeScript in ESM Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/tsx-require.md Import the `require` function from `tsx/cjs/api` to use it within an ESM environment. Pass `import.meta.url` as the second argument for context. ```javascript import { require } from 'tsx/cjs/api' const tsLoaded = require('./file.ts', import.meta.url) const tsFilepath = require.resolve('./file.ts', import.meta.url) ``` -------------------------------- ### Scoped Registration with Namespace Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/register-esm.md Registers the TSX enhancement within a specific namespace, providing a private import method. ```APIDOC ## Scoped Registration ### Description Allows for scoped registration of the TSX enhancement using a unique namespace. This provides a private `import` method that does not share cache with global or other scoped registrations. ### Usage ```js import { register } from 'tsx/esm/api' // Create a scoped API instance with a unique namespace const api = register({ namespace: Date.now().toString() }) // Use the namespaced import method to load files // The second argument is the current file path (import.meta.url) const loaded = await api.import('./file.ts', import.meta.url) // Importing the same file again within the same namespace will yield a cache hit const loaded2 = await api.import('./file.ts', import.meta.url) // Unregister the scoped API instance api.unregister() ``` ### Parameters - `namespace` (string): A unique identifier for the scope. ### Returns - `api`: An object with an `import` method and an `unregister` method. - `api.import(specifier: string, referrer: string)`: Dynamically imports a module within the specified namespace. - `api.unregister()`: Unregisters the scoped API instance. ``` -------------------------------- ### Scoped Registration Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/register-cjs.md Registers the tsx enhancement within a specific namespace, returning a private `require` method for loading files. This prevents global interference. ```APIDOC ## Scoped Registration ### Description Registers the tsx enhancement within a specified namespace, providing a private `require` method for loading files. This is useful for isolating the enhancement. ### Method `tsx.register({ namespace: string }) ### Parameters #### Request Body - **namespace** (string) - Required - A unique string to identify the namespace for this registration. ### Returns - `api` (object) - An object containing a `require` method and an `unregister` method. - `api.require(path: string, filename: string)`: Loads and compiles a file within the scoped namespace. - `api.unregister()`: Unregisters the enhancement for this specific namespace. ### Request Example ```js const tsx = require('tsx/cjs/api') const api = tsx.register({ // Pass in a unique namespace namespace: Date.now().toString() }) // Pass in the request and the current file path const loaded = api.require('./file.ts', __filename) api.unregister() ``` ### Response #### Success Response - `api` (object) - An object with `require` and `unregister` methods. #### Response Example (No specific response body, returns an API object) ``` -------------------------------- ### tsImport() Usage Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/ts-import.md Demonstrates how to use the tsImport() function for dynamic TypeScript imports in both ESM and CommonJS environments. Note that this function does not cache loaded modules. ```APIDOC ## ESM Usage ```js import { tsImport } from 'tsx/esm/api' const loaded = await tsImport('./file.ts', import.meta.url) // If tsImport is used to load file.ts again, // it does not yield a cache-hit and re-loads it const loadedAgain = await tsImport('./file.ts', import.meta.url) ``` ## CommonJS Usage ```js const { tsImport } = require('tsx/esm/api') const loaded = await tsImport('./file.ts', __filename) ``` ``` -------------------------------- ### Specify Custom tsconfig.json Path Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/node-cli.md Set the `TSX_TSCONFIG_PATH` environment variable to point to a custom `tsconfig.json` file when running TypeScript with Node.js. ```sh TSX_TSCONFIG_PATH=./path/to/tsconfig.custom.json node --import tsx ./file.ts ``` -------------------------------- ### Exclude Files Using Glob Patterns in Watch Mode Source: https://github.com/privatenumber/tsx/blob/master/docs/watch-mode.md Employ glob patterns with the --exclude flag to ignore sets of files or directories. Ensure glob patterns are quoted to prevent shell expansion. ```bash tsx watch --exclude "./data/**/*" ./file.ts ``` -------------------------------- ### Scoped Registration with Namespace Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/register-esm.md Register TSX enhancement within a specific namespace to avoid affecting the global runtime. This returns a private `import()` method for loading files within that namespace, with cache-hit behavior specific to the namespace. ```javascript import { register } from 'tsx/esm/api' const api = register({ // Pass in a unique namespace namespace: Date.now().toString() }) // Pass in the request and the current file path // Since this is namespaced, it will not cache hit from prior imports const loaded = await api.import('./file.ts', import.meta.url) // This is using the same namespace as above, so it will yield a cache hit const loaded2 = await api.import('./file.ts', import.meta.url) api.unregister() ``` -------------------------------- ### Scoped tsx Registration with Namespace Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/register-cjs.md Register tsx enhancement within a specific namespace to avoid affecting the global runtime. This returns a private `require()` method for loading files within that scope. Remember to call `api.unregister()` when done. ```javascript const tsx = require('tsx/cjs/api') const api = tsx.register({ // Pass in a unique namespace namespace: Date.now().toString() }) // Pass in the request and the current file path const loaded = api.require('./file.ts', __filename) api.unregister() ``` -------------------------------- ### Register TSX Enhancement Globally Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/register-esm.md Use this to register the TSX enhancement for the entire runtime environment. Call `unregister()` when it's no longer needed. ```javascript import { register } from 'tsx/esm/api' // Register tsx enhancement const unregister = register() await import('./file.ts') // Unregister when needed unregister() ``` -------------------------------- ### Import TypeScript in CommonJS Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/tsx-require.md Use `tsx.require()` to import TypeScript files within a CommonJS environment. The current file path must be provided as the second argument for correct resolution. ```javascript const tsx = require('tsx/cjs/api') const tsLoaded = tsx.require('./file.ts', __filename) const tsFilepath = tsx.require.resolve('./file.ts', __filename) ``` -------------------------------- ### Require tsx for CommonJS Source: https://github.com/privatenumber/tsx/blob/master/docs/dev-api/entry-point.md Use require('tsx/cjs') at the top of your entry-file to load TS files within a CommonJS environment. This allows you to use require() for your TypeScript files. ```js require('tsx/cjs') // Now you can load TS files require('./file.ts') ```