swc-node icon indicating copy to clipboard operation
swc-node copied to clipboard

@swc-node/register can not handle es modules

Open cschroeter opened this issue 4 years ago • 3 comments

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 avatar Dec 15 '21 11:12 cschroeter

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());
})();

cschroeter avatar Dec 15 '21 11:12 cschroeter

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

jameshfisher avatar Jan 06 '22 12:01 jameshfisher

Same problem here...

danielyogel avatar Jan 12 '22 23:01 danielyogel

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.

jameshfisher avatar Jan 19 '23 11:01 jameshfisher