【问题标题】:TypeScript & NodeJS: Exports is not defined in ES module scopeTypeScript 和 NodeJS:ES 模块范围内未定义导出
【发布时间】:2022-02-02 20:33:45
【问题描述】:

我已经用 Import/Export 语法编写了我的 NodeJS JavaScript 文件,并且我的 package.json 有 "type" : "module"

问题是tsc构建代码后,/build/server.js中的转译代码无法运行。它说Exports is not defined in ES module scope

这是我的tsconfig.json

{
  "compilerOptions": {
    "resolveJsonModule": true,
    "incremental": true,
    "target": "es2019" ,
    "module": : "commonjs",
    "allowJs": true ,
    "outDir": "./build",
    "strict": true ,
    "noImplicitAny": false,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictBindCallApply": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true ,
    "alwaysStrict": true ,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true ,
    "inlineSourceMap": true ,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true ,
    "forceConsistentCasingInFileNames": true,
    "useUnknownInCatchVariables": false
  }
}

如果我删除 "module" : "commonjs" 并添加 "moduleResolution": "Node",我的导入会出现不同的错误:

找不到从 /build/server.js 导入的模块 /build/constants 模块 /build/constants.js 确实存在,但在我的代码中我没有将 .js 添加到我的导入中,所以我像这样import {CONSTANTS} from 'constants' 导入它。

在一个 TypeScript 文件中,导入其他 TypeScript 文件时,导入的应该是import {CONSTANTS} from constants.js 还是import {CONSTANTS} from constants.ts 还是import {CONSTANTS} from constants,这就是我现在所拥有的。

我是 TypeScript 的新手。解决我遇到的这个问题的最佳方法是什么?

谢谢

【问题讨论】:

    标签: javascript node.js typescript


    【解决方案1】:

    我找到了解决方案。 "type" : "module" 必须从 package.json 中删除

    【讨论】:

      猜你喜欢
      • 2022-09-28
      • 2017-09-29
      • 1970-01-01
      • 2014-10-05
      • 2018-05-16
      • 1970-01-01
      • 2017-09-14
      • 1970-01-01
      • 2015-05-08
      相关资源
      最近更新 更多