使用ts-node执行打字稿代码会导致“无法在模块外部使用import语句”错误

时间:2020-07-13 15:38:34

标签: node.js typescript compilation tsconfig ts-node

我正在尝试运行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(我当然不能这样做),则上面的命令可以正常工作。我不确定实际上是哪种配置引起了问题。

1 个答案:

答案 0 :(得分:1)

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

定位

tsconfig.node.json

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