使用 ts-node 执行打字稿代码"Cannot use import statement outside a module"错误



我正在尝试运行apollo-server,我编写的代码在TypeScript中。

我的代码文件夹包含一个tsconfig.json,它看起来像这样:

{
"compilerOptions": {
"target": "esnext",
"lib": [
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true
},
"include": [
"server"
]
}

我运行的命令如下:

$ npx ts-node ./server/index.ts

如果我删除tsconfig.json(当然我做不到(,上面的命令就可以正常工作。我不确定是哪种配置导致了问题。

您正在搜索的设置是"module": "commonjs"。由于ts节点在nodejs环境中执行代码,因此必须使用其模块系统。如果您需要将您的配置作为项目的默认配置,您可以创建第二个tsconfigtsconfig.node.json,并使用ts-node --project <tsconfig.json>将其作为目标

tsconfig.node.json:

{
"extends": "./",
"compilerOptions": {
"module": "commonjs",
},
}

相关内容

最新更新