I am trying to run node 14 with my package.json set as module:
"type": "module",
If I run this command on a typescript file:
node --loader ts-node/esm.mjs --experimental-top-level-await ./src/scripts/ts-build.ts --trace-warnings --experimental-json-modules
and I have extensionless imports like this in a typescript file
import { logger } from './logger';
I get
ERR_MODULE_NOT_FOUND
But if I change it to
import { logger } from './logger.js';
It works.
Why is this?
I solved it with these experimental features on Node v14.15.0
.
node --loader ts-node/esm --experimental-specifier-resolution=node your/entry.ts
But if you just want command node
, ts-node
or webpack serve
to work with typescript entry files with import statements(such as server.ts or webpack.config.ts), you can resolve the issue by setting compilerOptions
under ts-node
option in your tsconfig.ts.
{
"ts-node": {
"compilerOptions": {
"module": "CommonJS"
}
},
"compilerOptions": {
"target": "ES6",
"module": "ES6",
"moduleResolution": "Node",
"esModuleInterop": true
},
"include": [
// below entries are just examples
"src/**/*",
"server.ts"
"webpack.config.ts"
]
}
If we take a look at the spec there's this section which states:
The current specifier resolution does not support all default behavior of the CommonJS loader. One of the behavior differences is automatic resolution of file extensions and the ability to import directories that have an index file.
There's another section which states:
A file extension must be provided when using the import keyword. Directory indexes (e.g. './startup/index.js') must also be fully specified.
So it seems that the extension is actually necessary. Howvever, there's the option --experimental-specifier-resolution
which you try setting to --experimental-specifier-resolution=node
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With