Recently I tried setting up a node project where I use ES6 import
statements and top-level await
, and I came across a weird problem.
While using npx ts-node index.ts
to run my application, I found that it didn't know my file extension .ts
:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /home/zhyp/Code/ts-test/src/index.ts
So after some research, I came across the esm
flag (npx ts-node --esm index.ts
), after running with this command, my files actually could not be found:
throw new ERR_MODULE_NOT_FOUND(
^
CustomError: Cannot find module '/home/zhyp/Code/ts-test/src/imported-file' imported from /home/zhyp/Code/ts-test/src/index.ts
So after more research, I've tried adding the .js
extension to all imports, which weirdly enough worked, but not if I changed those files' extensions to .ts
, because then I would need to enabled allowImportingTsExtensions
in my tsconfig.json
, and enable notEmit
that would prevent me from using tsc
to build anything.
Can anyone help me understand why exactly this setup won't work?
Necessary files to reproduce:
tsconfig.json
{
"compilerOptions": {
"target": "es2022",
"module": "es2022",
"rootDir": "src",
"resolveJsonModule": true,
"allowJs": true,
"outDir": "build",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true,
"skipLibCheck": true
}
}
package.json
{
"name": "typescript-node",
"version": "1.0.0",
"description": "TypeScript Template with Node.js",
"main": "src/index.js",
"scripts": {
"start": "nodemon --exec 'ts-node' src/index.ts"
},
"dependencies": {
"@types/node": "14.14.29",
"ts-node": "10.9.1",
"typescript": "5.0.4"
},
"devDependencies": {
"@types/express": "^4.17.6",
"nodemon": "1.18.4"
},
"keywords": [],
"type": "module"
}
index.ts
import test from "./imported-file";
console.log(test);
imported-file.ts
export default {};