I am trying to run a single TypeScript file inside an NX
monorepo using ts-node
but I keep getting errors when importing local modules.
npx ts-node apps/sanity/src/sanity.ts
(node:22816) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
Cannot use import statement outside a module
Setting "type": "module"
in the package.json
in the workspace root, and then running the command again results in this error:
npx ts-node apps/sanity/src/sanity.ts
Unknown file extension ".ts" for /Users/maverik/Projects/project-zed/apps/sanity/src/sanity.ts
at new NodeError (internal/errors.js:322:7)
at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:71:15)
at Loader.getFormat (internal/modules/esm/loader.js:105:42)
at Loader.getModuleJob (internal/modules/esm/loader.js:243:31)
at async Loader.import (internal/modules/esm/loader.js:177:17)
at async Object.loadESM (internal/process/esm_loader.js:68:5)
at async handleMainPromise (internal/modules/run_main.js:59:12) {
code: 'ERR_UNKNOWN_FILE_EXTENSION'
How can I run a single typescript file using ts-node
inside an NX monorepo?
I added a new tsconfig.demo.json
file to the project with the following options:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"types": ["node"],
"module": "ESNext", // this option
"moduleResolution": "Node", // this option
"esModuleInterop": true // this option
},
"ts-node": {
"esm": true, // this option
"experimentalSpecifierResolution": "node". // this option
},
"exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"],
"include": ["src/**/*.ts"]
}
And then ran this command:
npx ts-node --project apps/sanity/tsconfig.demo.json apps/sanity/src/main.ts