【问题标题】:Nodejs, TypeScript, ts-node-dev & top-level awaitNodejs、TypeScript、ts-node-dev 和顶级等待
【发布时间】:2021-02-13 00:57:15
【问题描述】:

在需要顶级等待之后,我现在花了一个小时寻找新错误的解决方案。到目前为止我尝试过的所有其他方法都没有解决错误,例如将 "type": "module" 添加到 package.json 文件中。

启动服务时报错信息为Cannot use import statement outside a module。 如果我将更改 "module": "ESNext", 恢复为 "module": "commonjs",,它可以正常工作(除了必须删除 await 关键字并以某种方式重构以在没有 await 的情况下工作)。

另外,我使用 ts-node-dev 运行服务,可以在 package.json 文件中看到。

  • 我需要的新包是kafkajs。
  • 节点版本:v14.9.0
  • TypeScript 版本:4.0

package.json

{
  "name": "",
  "version": "1.0.0",
  "description": "microservice",
  "main": "src/index.ts",
  "author": "",
  "type": "module",
  "license": "MIT",
  "scripts": {
    "dev": "NODE_ENV=development tsnd --respawn --files src/index.ts",
    "prod": "NODE_ENV=production tsnd --respawn --transpile-only --files src/index.ts",
    "test": "mocha --exit -r ts-node/register tests/**/*.spec.ts",
    "eslint": "eslint src/**/*.ts"
  },

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "node",
    "outDir": "dist",
    "sourceMap": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  },
  "ts-node": {
    "files": true,
    "transpileOnly": true
  },
  "include": ["src/**/*.ts", "declariations/**.d.ts"],
  "exclude": ["node_modules", ".vscode"]
}

【问题讨论】:

    标签: node.js typescript async-await top-level-await


    【解决方案1】:

    我知道,这个问题已经很老了,但是对于像我今天早些时候那样通过这个问题的人:

    我只是设法让它工作。不是直接用ts-node-dev,而是用nodemonts-node的组合。

    你需要安装nodemonts-node然后,假设你的入口文件是src/index.ts,你可以使用这个命令:

    nodemon --ext ts --loader ts-node/esm --experimental-specifier-resolution node src
    

    (使用 Node v16.13.0 测试)

    这是我弄清楚的关键帖子:https://github.com/TypeStrong/ts-node/issues/1007

    【讨论】:

      【解决方案2】:

      TL;DR:不要将 ECMAScript 模块与 ts-node 或 ts-node-dev 一起使用(暂时);只需重构顶级等待输出

      今天我跌倒了同一个兔子洞,从无害的错误开始:

      Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
      

      因此,我倾向于编辑我的tsconfig.json 并将module 设置为esnext,这反过来又迫使我将moduleResolution 设置为node,最后将type: module 添加到我的@987654331 @。我没有意识到(而且 IMO 他们不应该在错误消息中建议这一点——你可以简单地重构顶级等待),这将 NodeJS 的模块解析策略从 CommonJS 切换到 ESM。这实际上是一件大事,原因有很多:

      我觉得此时(2020 年 12 月)NodeJS 生态系统仍在从经典的 CommonJS 模块向新的 ECMAScript 模块过渡。因此,像 ts-node 或 ts-node-dev 这样的其他技术也在过渡,并且支持可能很不稳定。我的建议是坚持使用 CommonJS,直到尘埃落定并且这些东西“开箱即用”。

      【讨论】:

      • 被否决为“重构顶级等待”并不能解决如何使用顶级等待的问题。没有顶级等待是默认状态,因此建议是给定的。
      • 我的回答本质上是“你不能”,并解释为什么不能。仅仅因为答案不是你所期望的并不意味着它是一个糟糕的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 2021-09-21
      • 2021-10-03
      • 2020-08-14
      • 2022-09-28
      • 1970-01-01
      • 2020-11-04
      相关资源
      最近更新 更多