How to dynamically import .js files in NodeJS with TypeScript?

Viewed 693

tl;dr I can import a .mjs file dynamically but not a .js one, even it has the same content.

When I run node --loader ts-node/esm --experimental-specifier-resolution=node ./src/server.ts for a project which imports an external file with import() function to run the ES6-style-exported function it contains as follows:

// external.js
export default () => {
    return 'Hello World'
}
// src/server.ts
// ...
export const applyFunction = async () => {
  const {default: transform} = await import(`${pathToFolder}/external.js`)
  const result = transform()
}

it throws an error:

(node:6132) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
[ERR] Unexpected token 'export'

I also receive that warning even if I have "type": "module" set in my package.json.

When I change the file extension to .mjs, it runs as it should: no warning, no errors

Is there any way I can have my external files with .js extension? Is it me or ts-node who should fix something?

P.S "type": "module" statement cannot be removed due to some other restrictions.

0 Answers
Related