Skip to content

ESM support: soliciting feedback #1007

Description

@cspotcode

Please use this ticket to provide feedback on our native ESM support. Your involvement is greatly appreciated to ensure the feature works on real-world projects.

Experimental warning

Node's loader hooks are EXPERIMENTAL and subject to change. ts-node's ESM support is as stable as it can be, but it relies on APIs which node can and will break in new versions of node.

When node breaks their APIs, it breaks loaders using their APIs. You have been warned!

Third-party docs: "Guide: ES Modules in NodeJS"

Someone has been maintaining a great reference document explaining how to use ts-node's ESM loader.

Guide: ES Modules in NodeJS

First-party docs

Our website explains the basics:

CommonJS vs native ECMAScript modules
Options: esm

Usage

Requirements

  • Set "module": "ESNext" or "ES2015" so that TypeScript emits import/export syntax.
  • Set "type": "module" in your package.json, which is required to tell node that .js files are ESM instead of CommonJS. To be compatible with editors, the compiler, and the TypeScript ecosystem, we cannot name our source files .mts nor .mjs.
  • Include file extensions in your import statements, or pass --experimental-specifier-resolution=node Idiomatic TypeScript should import foo.ts as import 'foo.js'; TypeScript understands this.
    • The language service accepts configuration to include the file extension in automatically-written imports. In VSCode:
      image

Invocation

ts-node-esm ./my-script.ts

ts-node --esm ./my-script.ts

# If you add "esm": true to your tsconfig, you can omit the CLI flag
ts-node ./my-script.ts

# If you must invoke node directly, pass --loader
node --loader ts-node/esm ./my-script.ts

# To force the use of a specific tsconfig.json, use the TS_NODE_PROJECT environment variable
TS_NODE_PROJECT="path/to/tsconfig.json" node --loader ts-node/esm ./my-script.ts

# To install the loader into a node-based CLI tool, use NODE_OPTIONS
NODE_OPTIONS='--loader ts-node/esm' greeter --config ./greeter.config.ts sayhello

ts-node-esm / --esm / "esm": true work by spawning a subprocess and passing it the --loader flag.

Configuration

When running ts-node --esm, ts-node-esm, or ts-node all CLI flags and configuration are parsed as normal. However, when passing --loader ts-node/esm, the following limitations apply:

  • tsconfig.json is parsed.
  • CLI flags are not parsed.
  • Environment variables are parsed.
  • ts-node must be installed locally, not globally. npm install ts-node or yarn add ts-node.

tsconfig will be resolved relative to process.cwd() or to TS_NODE_PROJECT. Specify ts-node options in your tsconfig file. For details, see our docs.

Use TS_NODE_PROJECT to tell ts-node to use a specific tsconfig, and put all ts-node options into this config file.

Versioning

As long as node's APIs are experimental, all changes to ESM support in ts-node, including breaking changes, will be released as minor or patch versions, NOT major versions. This conforms to semantic versioning's philosophy for version numbers lower than 1.0. Stable features will continue to be versioned as normal.

node's API change: v16.12.0, v17.0.0

Node made a breaking change in their ESM API in version 17, backported to 16.12.0. It may also be backported to 14 and 12.
This is the change: nodejs/node#37468

ts-node automatically supports both APIs, thanks to #1457. This relies on hard-coded version number checks. If/when this is backported to node 14 and 12, we will publish a new version of ts-node with the appropriate version number checks. Be sure you are always using the latest version of ts-node to avoid problems.





Note: things below this line may be out-of-date or inaccurate. These notes were used during initial implementation, but have not been updated since

Pending development work

  • Make resolution lookup use our fs caches
  • Create esm-script.mjs to do --script-mode?
    • Can read process.argv for config resolution?
  • Implement require('ts-node').esmImport(module, 'import-path')
  • Throw error when CJS attempts to require ESM, matching node's behavior for .js
    • See below: "Changes to existing functionality" > "require() hook"

The proposal

Below is the official proposal, explaining our implementation in detail.


I am asking node's modules team questions here: nodejs/modules#351

I was reading the threads about ESM support in ts-node, e.g. #935.

The @K-FOSS/TS-ESNode implementation is unfortunately incomplete; it does not attempt to typecheck. (it uses transpileModule)

So I did some research. Below is a proposal for ESM support in ts-node, describing the required behavior in detail.

This doesn't feel like an urgent feature to me, but I like having an official proposal we can work on.


Usage

node --loader ts-node/esm ./entrypoint.ts

Cannot be invoked as ts-node because it requires node flags; hooks cannot be enabled at runtime. This is unavoidable.

For simplicity, --require ts-node/register can be eliminated, because ts-node/esm automatically does that.

Alternatively, we publish an experimental ts-node-esm entry-point which invokes a node subprocess.


Don't forget allowJs! Affects the treatment of .js files. (Not .mjs nor .cjs because the TS language service won't look at them)

ESM hooks

Must implement ESM hooks to resolve extensionless imports to .ts files, resolve .js to .ts, classify .ts(x) and .jsx files as CJS or MJS, and compile .ts(x) and .jsx files.

resolve() hook:

Match additional file extensions: .ts, .tsx, .jsx.

Resolve .ts, .tsx, and .jsx if the import specifier says .js. Obey preferTsExts when doing this.

_

[Good idea?] Always ask default resolver first. If it finds something, we should not interfere.

--experimental-specifier-resolution=node does not obey require.extensions, unfortunately, so we can't use that.

getFormat hook:

If the resolved file is .ts, .tsx, or .jsx, behave as if extension was .js: use node's package.json discovery behavior to figure out if ESM or CJS.

This can be accomplished by appending .js to the URL path and delegating to built-in getFormat hook.

transformSource hook:

Same as today's code transformer. Relies on projects to be configured correctly for import/export emit.

Changes to existing functionality

require() hook

  • Use same getFormat logic to determine if node will treat file as CJS or ESM.
  • NOTE node already detects and throws some errors on its own. But if require.resolve points to a .ts file, we need to make the determination.
  • If ESM, throw the same error as NodeJS ("cannot load ESM via require()")

require() code transform

  • Must somehow allow import() calls.
  • Force consumers to use require('ts-node').esmImport(module, 'import-path')?

ts-node bin entry-point

ts-node CLI does NOT need to support import()ing ESM.

WHY? Because ESM hooks are an experimental feature which must be enabled via node CLI flag.

Thus we will be loaded via --require, and Node is responsible for loading the entry-point, either triggering our hook or our require.extensions.

Allow import() in CJS

If "module": "commonjs", compiler transforms import() into __importStar

No way to change this without a custom transformer, which IMO is too much complexity at this time.

Users should run their code as ESM.

If they can't do that, we can recommend the following workaround:

// This is in a CommonJS file:
const dynamicallyImportedEsmModule = await require('ts-node').importESM('./specifier-of-esm-module', module);

Emit considerations

NOTE we have not implemented the following, although initially I thought we might. Instead, we assume tsconfig is configured for either ESM or CJS as needed

We could intelligently emit both "module": "esnext" and "module": "commonjs" depending on the classification of a file.

In transpile-only mode this is simple. Call transpileModule with different options.

When typechecking, we can pull SourceFile ASTs from the language service / incremental compiler.

We'll need a second compiler, one for each emit format. Or we can hack it by using transpileModule for all ESM output. transpileModule is incompatible with certain kinds of TS code, (can't do const enums) but it might work for a first-pass implementation.

Activity

  1. added
    researchNeeds design work, investigation, or prototyping. Implementation uncertain.
    on Apr 12, 2020
  2. cspotcode commented on Apr 24, 2020

    @cspotcode
    CollaboratorAuthor

    TODO: turns out, users can tell the language service to include the .js file extension with automatically-written imports. So we do not need to automatically add them, though we do need to check if a .js import might point to a .ts or .tsx file.

    The option is passed to the language service in a ts.UserPreferences object.
    https://discordapp.com/channels/508357248330760243/640177429775777792/703301413337432114

  3. cspotcode commented on Apr 27, 2020

    @cspotcode
    CollaboratorAuthor

    I was trying to figure out if ts-node needs to automatically switch the "module" option between CommonJS and ESNext depending if we need to emit CommonJS or ESM. I concluded we do not want to do this. Here's an explanation anyway, in case I am proven wrong.

    Today, ts-node respects the tsconfig's module option. Users are required to set it appropriately. If the user incorrectly sets module to ESNext and then tries to require() a TS file, they get an error because the emitted code has import statements.

    Alternatively, we can automatically override the module option to be CommonJS when emitting for require() and ESNext when emitting for ESM. This allows a single tsconfig to be used for both ESM and CommonJS.

    After thinking about this, it doesn't make sense. Users will choose either ESM or CommonJS via their package.json file. They won't do a mix of both. Also, this would get pretty messy since we'd be doing something that doesn't match tsc's output.

    Nevertheless, if we wanted to implement this:

    If the module option is already correct, we can use the languageService's getEmitOutput() like we do today. If not, we can grab a reference to the SourceFile and transform it using the same technique as transpileModule's implementation. This allow custom emit while avoiding an expensive parse.

    TypeScript has an internal sourceFileAffectingCompilerOptions array. If any of those options differ, a SourceFile cannot be reused. However, some are only relevant if you care about diagnostics. For swapping out the module flag, I think SourceFile can always be reused.

  4. cspotcode commented on May 3, 2020

    @cspotcode
    CollaboratorAuthor

    We have released an experimental implementation of this in v8.10.1. Please test and share your feedback here.

  5. pinned this issue on May 3, 2020
  6. changed the title [-]ESM support: Detailed proposal[/-] [+]ESM support: Current status, proposal, soliciting feedback[/+] on May 3, 2020
  7. changed the title [-]ESM support: Current status, proposal, soliciting feedback[/-] [+]ESM support: Current implementation, soliciting feedback[/+] on May 3, 2020
  8. changed the title [-]ESM support: Current implementation, soliciting feedback[/-] [+]ESM support: soliciting feedback[/+] on May 3, 2020
  9. chpeters commented on May 3, 2020

    @chpeters

    Thanks @cspotcode for the release! Everything seems be working minus one snafu. Importing named exports don't seem to be working, but this may be a Node module quirk. For example in index.ts:

    import { graphql } from 'graphql';

    will cause a syntax error of:

    SyntaxError: The requested module 'graphql' does not provide an export named 'graphql'
    

    but this can be solved by using destructuring:

    import Graphql from 'graphql';
    const { graphql } = Graphql;

    Any way to support importing named exports in ts files?

  10. blakeembrey commented on May 3, 2020

    @blakeembrey
    Member

    @chpeters I'd guess that would be because graphql is actually CommonJS and not an ES module. You can read more about it here: https://nodejs.org/api/esm.html#esm_interoperability_with_commonjs. Unfortunately it'll probably be messy for a while with TypeScript since the imports syntax is overloaded to represent both CommonJS and native ES modules.

  11. NeilujD commented on May 8, 2020

    @NeilujD

    Using mocha and TypeScript with ES modules I am facing an issue and I don't quite understand it.

    Running this cmd as my test cmd :

    node --experimental-modules --loader ts-node/esm.mjs ./node_modules/mocha/bin/mocha --extension ts

    I get this error :

    import './unit/authentication.js';
    ^^^^^^
    
    SyntaxError: Cannot use import statement outside a module

    What did I do wrong ?

    PS: I have my tsconfig.json module attribute set to "ES2015", my package.json type attribute to "module", ts-node installed locally

  12. cspotcode commented on May 8, 2020

    @cspotcode
    CollaboratorAuthor
  13. NeilujD commented on May 8, 2020

    @NeilujD

    This is my project architecture :

    src
      |_index.ts
    test
      |_tests.ts
      |_unit
          |_authentication.ts
    package.json
    tsconfig.json
    

    My package.json :

    {
      "name": "my-project",
      "version": "1.0.0",
      "description": "My project",
      "main": "lib/index",
      "type": "module",
      "files": [
        "lib/**/*"
      ],
      "directories": {
        "test": "test"
      },
      "scripts": {
        "build": "tsc",
        "test": "node --experimental-modules --loader ts-node/esm.mjs ./node_modules/mocha/bin/mocha --extension ts"
      },
      "devDependencies": {
        "@types/chai": "^4.2.11",
        "@types/mocha": "^7.0.2",
        "@types/node": "^13.13.5",
        "chai": "^4.2.0",
        "mocha": "^7.1.2",
        "ts-node": "^8.10.1",
        "typescript": "^3.8.3"
      }
    }

    My tsconfig.json :

    {
      "compilerOptions": {
        "target": "ES2015", 
        "module": "ES2015", 
        "lib": ["es6"], 
        "declaration": true,
        "outDir": "lib",
        "rootDir": "src",
        "strict": true, 
        "noImplicitAny": true,   
        "moduleResolution": "node",   
        "esModuleInterop": true,  
        "forceConsistentCasingInFileNames": true
      },
      "exclude": [
        "test/"
      ]
    }

    My test/tests.ts :

    import './unit/authentication.js'

    Typescript is building my files right.
    The npm run test cmd returns throw the error I wrote before.

    Do you need more context ?

  14. cspotcode commented on May 8, 2020

    @cspotcode
    CollaboratorAuthor

    @NeilujD this is perfect, thanks.

    It looks like, due to missing features in node's ESM support, mocha is using a hack to figure out whether a file should be loaded as ESM or CJS.
    https://github.com/mochajs/mocha/blob/master/lib/esm-utils.js#L4-L23

    ts-node's require() hook will need to be updated to match the error behavior of node's .js hook. When you try to require() a TS file that should be treated as ESM, we should throw an error.

    At first I thought mocha could simply import() everything, since it automatically switches to CommonJS loading as needed. However, that would require our ESM hook to be installed in order to resolve and classify .ts files. They're forced to use require() to cater to legacy require() hooks.

  15. 431 remaining items

  16. nickserv commented on Jan 6, 2024

    @nickserv

    Note that as of Node 20 you'll need to name it ts-loader.js to work around ERR_UNKNOWN_FILE_EXTENSION.

  17. crfrolik commented on Mar 1, 2024

    @crfrolik
    node --import "data:text/javascript,import {register} from 'node:module'; import {pathToFileURL} from 'node:url'; register('ts-node/esm', pathToFileURL('./'))" my-script.ts

    It works on Node.js v20.10.0. 😢

    But you can create a file named ts-loader.js:

    import {register} from 'node:module'
    import {pathToFileURL} from 'node:url'
    
    register('ts-node/esm', pathToFileURL('./'))

    And then:

    node --import ./ts-loader.js my-script.ts

    Remember: Don't write the loader path as ts-loader.js (if loader file is located in your source). But make sure write it with relative path: ./ts-loader.js!

    This solution led to an error for me:

    file:///<path-to-my-app/myapp.ts:2
    Object.defineProperty(exports, "__esModule", { value: true });
                          ^
    
    ReferenceError: exports is not defined in ES module scope
        at file:///<path-to-my-app/myapp.ts:2:23
        at ModuleJob.run (node:internal/modules/esm/module_job:195:25)
        at async ModuleLoader.import (node:internal/modules/esm/loader:336:24)
        at async loadESM (node:internal/process/esm_loader:34:7)
        at async handleMainPromise (node:internal/modules/run_main:106:12)
    

    Node.js v18.19.0

  18. GaoJuqian commented on Mar 27, 2024

    @GaoJuqian

    I used the graphql plugin of jetbrains idea editor, and the following error occurred.

    Node.js v20.11.0

    8097-graphql

    Code & tsconfig
    image

    Error

    java.lang.Throwable: (node:79373) ExperimentalWarning: `--experimental-loader` may be removed in the future; instead use `register()`:
    --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register("ts-node/esm", pathToFileURL("./"));'
    (Use `node --trace-warnings ...` to show where the warning was created)
    Error: Cannot find module '/Users/gjq/WebstormProjects/MemberManagement/frontend/src/api/supabase' imported from /Users/gjq/WebstormProjects/MemberManagement/frontend/graphql.config.ts
        at finalizeResolution node_modules//ts-node@10.9.2_@types+node@20.11.30_typescript@5.4.3/node_modules//dist-raw/node-internal-modules-esm-resolve.js:366:11
        at moduleResolve node_modules//ts-node@10.9.2_@types+node@20.11.30_typescript@5.4.3/node_modules//dist-raw/node-internal-modules-esm-resolve.js:801:10
        at Object.defaultResolve node_modules//ts-node@10.9.2_@types+node@20.11.30_typescript@5.4.3/node_modules//dist-raw/node-internal-modules-esm-resolve.js:912:11
        at node_modules//ts-node@10.9.2_@types+node@20.11.30_typescript@5.4.3/node_modules//src/esm.ts:218:35
        at entrypointFallback node_modules//ts-node@10.9.2_@types+node@20.11.30_typescript@5.4.3/node_modules//src/esm.ts:168:34
        at node_modules//ts-node@10.9.2_@types+node@20.11.30_typescript@5.4.3/node_modules//src/esm.ts:217:14
        at addShortCircuitFlag node_modules//ts-node@10.9.2_@types+node@20.11.30_typescript@5.4.3/node_modules//src/esm.ts:409:21
        at resolve node_modules//ts-node@10.9.2_@types+node@20.11.30_typescript@5.4.3/node_modules//src/esm.ts:197:12
    

    When I changed it to import . js, this problem was solved.

    import {supabaseKey, supabaseUrl} from "./src/api/supabase.js";

  19. pksunkara commented on Jun 20, 2024

    @pksunkara

    When using require() of ESM modules in CommonJS code, Node v22 recently added support for --experimental-require-module flag (https://nodejs.org/en/blog/announcements/v22-release-announce#support-requireing-synchronous-esm-graphs).

    With this flag, it's now easy for CommonJS projects/code to slowly transition to ESM code dependency by dependency.

    The only issue is that ts-node doesn't seem to work with this flag properly and thus hinders adoption. Would appreciate if someone can point me so that I can contribute to ts-node to add this flag.

  20. lemanschik commented on Jul 4, 2024

    @lemanschik

    @pksunkara i need to point out that one of the implementation details of require('es-module') is that it does not support and will never support for internal reasons top level await

    to shim that and even add support for it to ts-node you can go with -r esm
    to require the NPM esm package which you did install via npm i esm.

    the -r -i flags of node allow to import or requeire stuff before intrinsics are froozen

    the esm package ads cross interop in userland. until node 22.4~ will unflag that require-module thing.

  21. pksunkara commented on Jul 4, 2024

    @pksunkara

    i need to point out that one of the implementation details of require('es-module') is that it does not support and will never support for internal reasons top level await

    Of course, but many other use cases exist where the flag is enough.

  22. kopax commented on Aug 8, 2024

    @kopax

    To sum up.

    1. node-fetch v2 have a bug where it can drop transaction request silently Node.js script exits silently on some HTTPS requests node-fetch/node-fetch#1180
    2. node-fetch v3 does not work with cjs and ts-node
    3. node v18+ have native support for fetch, but it has the same bug as (1)

    I am working with ts-node in dev, cjs to distribute module in a lerna mono repo.

    Quite amazed I will have now to switch to another client library

  23. jakub-g commented on Oct 30, 2025

    @jakub-g

    PSA: If you're still using ts-node for some reason and struggle with ESM packages, try upgrading to nodejs@22.15.0+ (FYI: using tsx is way too slow for us because it tries to bundle way too much, haven't got time to dig in).

    I haven't done a thorough testing yet, but upgrading node made importing execa (ESM package) from CJS codebase just work ™️ without any code changes.

    For context:

    • our codebase is a huge monorepo with TypeScript + yarn (pnp) + ts-node
    • we invoke our scripts via yarn ts-node:register some/script.ts
      • ts-node:register is set up in package.json as: "ts-node:register": "cd $INIT_CWD && node -r $PROJECT_CWD/path/to/ts-node.js",
      • ts-node.js is require('ts-node').register(require('./tsconfig.tsnode.json'));
      • tsconfig.tsnode.json is as follows:
    {
        "swc": true,
        "compilerOptions": {
            "moduleResolution": "node",
            "module": "commonjs"
        }
    }
    
  24. thw0rted commented on Oct 30, 2025

    @thw0rted

    GH still doesn't support pagination for massive issues like this one, so I can't tell if anyone has suggested this recently, but since you've mentioned new Node features it's probably worth bringing up--experimental-strip-types. Docs here

    Between require-module and strip-types, I've been able to write and run TS natively without additional support libraries like ts-node. The exception has been Jest tests (which still transpile to CJS with ts-jest / Babel) and the NestJS framework (which I think transpiles with Webpack?). I was able to write new tests using Node's native test runner, which even has limited support for ESM mocking, but I think that side of things is still a little immature for production use. Still, might be worth a shot especially if you're starting a new project from scratch in late 2025.

  25. GabenGar commented on Nov 1, 2025

    @GabenGar

    @thw0rted
    The problem this won't work in actual production code as it requires your ENTIRE dependency tree of the project to be devoid of "transformative" typescript, which is next to impossible for anything involving bundlers (easily 1k of transitive dependencies).

  26. lemanschik commented on Nov 1, 2025

    @lemanschik

    @GabenGar node --experimental-transform-types another-example.ts

  27. thw0rted commented on Nov 2, 2025

    @thw0rted

    I've never really had luck trying to ship libraries in TS - as far as I can tell you always need to transpile your NPM packages down to JS, even with ts-node. (If that's wrong I'd love to read more about it?)

    Anyway, this is part of why I suggested using type stripping for new projects only. The instructions I linked include a suggestion to set up your tsconfig to only allow erasable syntax, which honestly is fine - enums have plenty of other issues and are easily replaced.

  28. darcyrush commented on Nov 2, 2025

    @darcyrush

    try upgrading to nodejs@22.15.0

    You are likely referring to all the work joyeecheung has been doing for require to work with ESM on NodeJS.

    Asides from ESM mocking, ESM usability issues are pretty much resolved on the latest NodeJS versions it seems.

    {
        "compilerOptions": {
            "moduleResolution": "node",
            "module": "commonjs"
        }
    }
    

    I understand you are just sharing your configuration without suggesting it, but for anyone else, please don't use this configuration - it is a legacy CJS setup. If you don't understand what I mean, deep dive into "Legacy Node Resolution".

    We have spent years "modernizing" our older projects to "modern" CJS configuration due to "Legacy Node Resolution" alone and all the gotchas with mocking and such...

  29. sgarner commented on Nov 2, 2025

    @sgarner

    Anyway, this is part of why I suggested using type stripping for new projects only. The instructions I linked include a suggestion to set up your tsconfig to only allow erasable syntax, which honestly is fine - enums have plenty of other issues and are easily replaced.

    This is fine for simple TS usage.

    It's inadequate for projects using popular libraries like NestJs or TypeORM which make heavy use of decorators. And it's a shame to lose support for other transpiled TS features.

    So type stripping is not a solution for everyone. ts-node still continues to be a valuable tool.

  30. thw0rted commented on Nov 2, 2025

    @thw0rted

    Great point about decorators, we use Nest in several projects and there's no way around including a build step, even if it's dynamic like ts-node. I feel like the standards track for decorators has kind of stalled, too, so we may be stuck with extra tooling indefinitely.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementresearchNeeds design work, investigation, or prototyping. Implementation uncertain.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions