Issue
I have a file in my src folder called foo.ts that looks like:
import * as cdk from 'aws-cdk-lib';
console.log('hello world');
const app = new cdk.App();
When I run ts-node src/foo.ts
I get the following error: SyntaxError: Cannot use import statement outside a module
If I remove the import console only it works... When I add "type": "module",
to package.json I get TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts
Here is my tsconfig.json:
{
// This is an alias to @tsconfig/node16: https://github.com/tsconfig/bases
"extends": "ts-node/node16/tsconfig.json",
// Most ts-node options can be specified here using their programmatic names.
"ts-node": {
// It is faster to skip typechecking.
// Remove if you want ts-node to do typechecking.
"transpileOnly": true,
"files": true,
"compilerOptions": {
// compilerOptions specified here will override those declared below,
// but *only* in ts-node. Useful if you want ts-node and tsc to use
// different options with a single tsconfig.json.
}
},
"compilerOptions": {
"outDir": "./dist/",
"baseUrl": ".",
"target": "es2017",
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react",
"downlevelIteration": true
},
"include": [
"src/**/*"
]
}
Solution
TL;DR: Remove the "module": "esnext"
line.
NodeJS's recent support of native ES Modules alongside the good-old CommonJS modules has introduced config confusion along with choice. For the time being, as the Typescript docs say, "you very likely want "CommonJS" for node projects".
How do you do this? The nice people at tsconfig/bases provide recommended tsconfig
for various environments. You are applying their Node16 recommendations with extends
, which is great. That is setting "module": "commonjs"
, and setting other config that a Node16 environment needs.
But then your compilerOptions
settings spoil the party by overriding the extends
settings with "module": "esnext"
, which is where the problems come in. Remove that line and the others that conflict with the tsconfig/bases
recommendations.
Tip: I find it more transparent to copy-paste the recommended settings into the compilerOptions
instead of indirectly referencing them with extends
, commenting where the recommendations begin and end. This way I am less likely to overwrite their good work.
Answered By - fedonev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.