Node.js 使用ts节点执行typescript代码会给出;无法在模块外部使用导入语句;错误
我正在尝试运行阿波罗服务器,我写的代码是在Node.js 使用ts节点执行typescript代码会给出;无法在模块外部使用导入语句;错误,node.js,typescript,compilation,tsconfig,ts-node,Node.js,Typescript,Compilation,Tsconfig,Ts Node,我正在尝试运行阿波罗服务器,我写的代码是在TypeScript中 我的代码文件夹包含一个tsconfig.json,如下所示: { "compilerOptions": { "target": "esnext", "lib": [ "esnext" ], "allowJs": true, "skipLibChec
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(当然我不能这么做),上面的命令可以正常工作。我不确定是哪个配置导致了问题。您正在搜索的设置是
“模块”:“commonjs”
。当ts节点在nodejs环境中执行代码时,您必须使用其模块系统。如果需要将配置作为项目的默认配置,则可以创建第二个tsconfigtsconfig.node.json
并使用ts node--project
tsconfig.node.json
:
{
"extends": "./",
"compilerOptions": {
"module": "commonjs",
},
}
我尝试将模块选项更改为
commonjs
。它不起作用。我在代码中有es6风格的导入。这会引发一个错误。我将尝试第二种方法,即提供一个单独的tsconfig.json
文件。您找到解决方案了吗?@Pablo目前,我暂时删除了似乎有效的模块选项。