- I created a new Node.js project with Node version 18.15.0. In the package.json, I added the field “type”: “module”.
{
"name": "ts-node-test",
"version": "1.0.0",
"description": "",
"type": "module",
"scripts": {
"test": "cross-env NODE_OPTIONS="--loader ts-node/esm" node index.cts"
},
"author": "",
"license": "ISC",
"devDependencies": {
"cross-env": "^7.0.3",
"ts-node": "^10.9.2",
"tslib": "^2.6.2",
"typescript": "^5.4.5"
},
"volta": {
"node": "18.15.0"
}
}
- The config of tsconfig.json is:
{
"$schema": "https://json.schemastore.org/tsconfig",
"ts-node": {
"transpileOnly": true,
"files": true,
"experimentalResolver":true,
"esm": true,
},
"compilerOptions": {
"outDir": "./dist",
"allowJs": true,
"allowSyntheticDefaultImports": true,
"baseUrl": "./",
"esModuleInterop": true,
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true,
"importHelpers": true,
"lib": [
"DOM",
"ESNext"
],
"module": "ESNext",
"moduleDetection": "force",
"moduleResolution": "node",
"noEmitOnError": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"target": "esnext",
"typeRoots": [
"./node_modules/@types",
]
},
"include": [
"index.cts",
"module.cts"
]
}
- I created a new file named index.cts with the following code:
import test from './module.cjs'
console.log(test(1, 2))
- In the same folder, the code of the file module.cts is:
export default (a: number, b: number) => a + b
- Afterward, I executed the script “test”, which produced the result without any errors.
3
It seems that .cts extension in Node.js can use module syntax for imports and exports.
why?
- The complete project information has been uploaded to GitHub. The GitHub repository can be found at: https://github.com/yaotusa/ts-node-test