简体   繁体   English

TypeScript & NodeJS:ES 模块中未定义导出 scope

[英]TypeScript & NodeJS: Exports is not defined in ES module scope

I have written my NodeJS JavaScript files with Import/Export syntax and my package.json has "type": "module"我用导入/导出语法编写了我的 NodeJS JavaScript 文件,我的 package.json 有"type": "module"

The problem is that after tsc builds the code, the transpiled code in /build/server.js cannot run.问题是tsc构建代码后,/build/ /build/server.js中的转译代码无法运行。 It says Exports is not defined in ES module scope它说Exports is not defined in ES module scope

Here's my tsconfig.json这是我的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
  }
}

if I remove "module": "commonjs" and add "moduleResolution": "Node" , I get a different error with my imports:如果我删除"module": "commonjs"并添加"moduleResolution": "Node" ,我的导入会出现不同的错误:

Cannot find module /build/constants imported from /build/server.js The module /build/constants.js does exist, but in my code I'm not adding.js to my imports, so I'm importing it like this import {CONSTANTS} from 'constants' .找不到从 /build/server.js 导入的模块 /build/constants模块 /build/constants.js 确实存在,但在我的代码中我没有将 .js 添加到我的导入中,所以我像这样import {CONSTANTS} from 'constants'import {CONSTANTS} from 'constants'

In a TypeScript file, when importing other TypeScript files, should the imports be like import {CONSTANTS} from constants.js or import {CONSTANTS} from constants.ts or import {CONSTANTS} from constants , which is what I have now.在 TypeScript 文件中,当导入其他 TypeScript 文件时,导入应该像import {CONSTANTS} from constants.jsimport {CONSTANTS} from constants.tsimport {CONSTANTS} from constants ,这就是我现在拥有的。

I'm new to TypeScript. What's the best way to solve this problem I'm having?我是 TypeScript 的新用户。解决我遇到的这个问题的最佳方法是什么?

Thanks谢谢

Updating tsconfig "module" and "target" to "ES6" solved the issue.将 tsconfig“module”和“target”更新为“ES6”解决了这个问题。

I found the solution.我找到了解决方案。 "type": "module" had to be removed from package.json "type": "module"必须从 package.json 中删除

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM