swc-project / swc-node

Faster ts-node without typecheck
MIT License
1.76k stars 73 forks source link

@swc-node/register can not handle es modules #634

Closed cschroeter closed 1 year ago

cschroeter commented 2 years ago
yarn run v1.22.17
$ node -r @swc-node/register index.ts
/home/christian/Workspaces/swc-modules/index.ts:141
undefined
      ^

Error [ERR_REQUIRE_ESM]: require() of ES Module /home/christian/Workspaces/swc-modules/node_modules/pkg-up/index.js from /home/christian/Workspaces/swc-modules/index.ts not supported.
Instead change the require of index.js in /home/christian/Workspaces/swc-modules/index.ts to a dynamic import() which is available in all CommonJS modules.
    at Object.newLoader [as .js] (/home/christian/Workspaces/swc-modules/node_modules/pirates/lib/index.js:141:7)
    at Object.<anonymous> (/home/christian/Workspaces/swc-modules/index.ts:2:14)
    at Module._compile (/home/christian/Workspaces/swc-modules/node_modules/pirates/lib/index.js:136:24)
    at Object.newLoader [as .ts] (/home/christian/Workspaces/swc-modules/node_modules/pirates/lib/index.js:141:7) {
  code: 'ERR_REQUIRE_ESM'
}

Here is an minimal demo of that isssue https://github.com/cschroeter/bug-swc-esmodules/blob/main/package.json

Here is how ts-node tackles the issue https://github.com/TypeStrong/ts-node/issues/1007

cschroeter commented 2 years ago

Although it works with node itself, you can not use dynamic imports like suggested in the error message above

(async () => {
  const { pkgUpSync } = await import("pkg-up");
  console.log("Hello World", pkgUpSync());
})();
jameshfisher commented 2 years ago

I just hit this issue too. @Brooooooklyn is there any workaround? (I can't change the code to use dynamic imports.)

danielyogel commented 2 years ago

Same problem here...

jameshfisher commented 1 year ago

Just found this, only to see I had the same problem a year ago ...

FYI: https://github.com/egoist/esbuild-register seems to not have this problem, so I'm switching to that for now.