[英]Executing typescript code using ts-node gives “Cannot use import statement outside a module” error
I am trying to run apollo-server
and the code I have written is in TypeScript
.我正在尝试运行
apollo-server
并且我编写的代码在TypeScript
中。
My code folder contains a tsconfig.json
which looks like this:我的代码文件夹包含一个
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"
]
}
The command I am running is below:我正在运行的命令如下:
$ npx ts-node ./server/index.ts
If I remove the tsconfig.json (which of course I can't do), the command above works fine.如果我删除 tsconfig.json (我当然不能这样做),上面的命令可以正常工作。 I am not sure which configuration is actually causing the problem.
我不确定哪个配置实际上导致了问题。
the setting you are searching is "module": "commonjs"
.您正在搜索的设置是
"module": "commonjs"
。 As ts-node is executing your code in the nodejs environment you have to use its module system.由于 ts-node 在 nodejs 环境中执行你的代码,你必须使用它的模块系统。 If you need your config as default for your project you can create a second tsconfig
tsconfig.node.json
and target it with ts-node --project <tsconfig.json>
如果您需要将您的配置作为项目的默认配置,您可以创建第二个 tsconfig
tsconfig.node.json
并使用ts-node --project <tsconfig.json>
定位它
tsconfig.node.json
: tsconfig.node.json
:
{
"extends": "./",
"compilerOptions": {
"module": "commonjs",
},
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.