【问题标题】:Executing typescript code using ts-node gives "Cannot use import statement outside a module" error使用 ts-node 执行打字稿代码会出现“无法在模块外使用 import 语句”错误
【发布时间】:2020-07-14 01:33:29
【问题描述】:

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

【问题讨论】:

  • 您找到解决方案了吗?
  • @Pablo 现在我暂时删除了似乎有效的模块选项。

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


【解决方案1】:

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

tsconfig.node.json:

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

【讨论】:

  • 我尝试将模块选项更改为commonjs。它没有用。我在代码中有 es6 样式的导入。它会为此引发错误。
  • 我将尝试提供单独的tsconfig.json 文件的第二种方法。
猜你喜欢
  • 1970-01-01
  • 2021-12-31
  • 2020-12-31
  • 2020-09-23
  • 2022-06-24
  • 2020-10-10
  • 1970-01-01
相关资源
最近更新 更多