我的src文件夹中有一个名为foo.ts的文件,如下所示:
import * as cdk from 'aws-cdk-lib';
console.log('hello world');
const app = new cdk.App();当我运行ts-node src/foo.ts时,我得到以下错误:SyntaxError: Cannot use import statement outside a module --如果我只删除导入控制台--它可以工作.当我将"type": "module",添加到package.json中时,就会得到TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts
这是我的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/**/*"
]
}发布于 2022-11-13 11:08:43
TL;DR:删除"module": "esnext"行。
NodeJS最近对自然ES模的支持,加上古老的CommonJS模块,带来了配置混乱和选择。目前,作为类型记录医生说,“您很可能希望节点项目的"CommonJS”。
你是怎么做到的?tsconfig/碱基的好人为各种环境提供了推荐的tsconfig。您正在使用他们的Node16建议和extends,这是很好的。这是设置"module": "commonjs",并设置Node16环境所需的其他配置。
但是,您的compilerOptions设置通过用"module": "esnext"覆盖extends设置而破坏了聚会,而这正是问题所在。删除该行和其他与tsconfig/bases建议相冲突的行。
提示:我发现将推荐的设置复制到compilerOptions中更透明,而不是通过extends间接引用它们,并在建议开始和结束的地方进行注释。这样我就不太可能掩盖他们的好作品了。
https://stackoverflow.com/questions/74408540
复制相似问题