Assume to have simple typescript program having two files:
src/hello.js
export default function hello() {
return 'Hello world'
}
src/say.js
import hello from './hello.js'
console.log(hello())
with the following tsconfig.json
{
"compilerOptions": {
"lib": ["es2023"],
"module": "node16",
"target": "es2022",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node16",
"allowSyntheticDefaultImports": true,
"outDir": "dist",
},
"include": ["src/**/*"]
}
and CommonJS type set in package.json
{
"type": "commonjs"
}
The problem is with ts-node
failing with the following error:
$ npx ts-node src/say.ts
Error: Cannot find module './hello.js'
Require stack:
- /Users/pawel/wrk/github/ts-sandbox/src/say.ts
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:1144:15)
at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (/Users/pawel/wrk/github/ts-sandbox/node_modules/@cspotcode/source-map-support/source-map-support.js:811:30)
at Function.Module._load (node:internal/modules/cjs/loader:985:27)
at Module.require (node:internal/modules/cjs/loader:1235:19)
at require (node:internal/modules/helpers:176:18)
at Object.<anonymous> (/Users/pawel/wrk/github/ts-sandbox/src/say.ts:1:1)
at Module._compile (node:internal/modules/cjs/loader:1376:14)
at Module.m._compile (/Users/pawel/wrk/github/ts-sandbox/node_modules/ts-node/src/index.ts:1618:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
at Object.require.extensions.<computed> [as .ts] (/Users/pawel/wrk/github/ts-sandbox/node_modules/ts-node/src/index.ts:1621:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ '/Users/pawel/wrk/github/ts-sandbox/src/say.ts' ]
}
This project works well when transpiled with tsc
and simply run node dist/say.js
. Also ts-node
alternatives (tsx src/say.ts
, tsimp src/say.ts
) work without issues.
Please find complete source code here.
What I’m missing with ts-node
please?
2
Answers
Just try removing the
.js
extension from the import line:src/say.js
first thing you are using import and it’s an feature of ES6
to use it in your project you have to set the type to "module"
by default it is "commonJs"
but if you are using typscript you have to remove "type" from your package.json
and it is doesn’t matter after transpiling ts into js it should work
also remove "module" from tsconfig.json
also set "target" to "nodeNext"
i hope that will works
second thing if you want to use js inside ts files you have to set "allowJs" property in "compilerOptions" in tsconfig
that’s in development phase