Typescript + Express = locked in a configuration loop

Viewed 240

I want to use ES6 modules in my app.

If I set "module": "es2020" or "module": "esnext" I get error To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

So I set the "type" : "module" in my package.json and get error saying Unknown file extension ".ts" So I can't use it. I can't use .mjs extension in Typescript too.

So I set "module": "commonjs" and "esModuleInterop": true and I can use ES6 modules with Typescript. But then I want to use import.meta and I get error saying that the 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'esnext', or 'system'.

I ran full circle. Is there a configuration that will allow me to use Typescript with Node without compromises? It's just import.meta now, but I am not sure what other features will be locked with this setup.

1 Answers

I solved the issue by using experimental feature. Instead of running ts-node command to run the code I used:

TS_NODE_PROJECT='./tsconfig.json' node --loader ts-node/esm ./src/index.ts

This allows me to use "type": "module" and "module": "esnext" together with Typescript, and I have both ES6 imports and access to import.meta.

I get a warning in console that the feature is experimental and could change at any time, so it's good to keep that in mind and reconsider if it's worth it.

Related