【问题标题】:Typescript not compiling correctly to commonjs/es2015Typescript 未正确编译为 commonjs/es2015
【发布时间】:2020-07-09 07:37:43
【问题描述】:

我正在运行 Node v14.5.0。我在开发环境中使用ts-node-dev

试图编译成 JS 总是报错。

一开始,我尝试过这个tsconfig

"target": "es5",
"module": "commonjs"
"outDir": "./dist",
"rootDir": "./src"

但是当我运行 tscnode dist/app.js 时,我收到以下错误:

UnhandledPromiseRejectionWarning: D:\Dev\src\entity\BaseEntity.ts:1
import {
^^^^^^

SyntaxError: Cannot use import statement outside a module

在做了一些研究之后,我发现我应该告诉 Node 使用将 "type": "module" 添加到 package.json 的模块。之后,错误变为:

Object.defineProperty(exports, "__esModule", { value: true });
                      ^

ReferenceError: exports is not defined

做了更多研究,我尝试了几种不同的方法,例如:

  • tsconfig"module": "commonjs" 更改为 "module": "es2015"

    这也会导致无法运行ts-node-dev。它抛出错误:Cannot use import statement outside a module

  • 添加到tsconfig "moduleResolution": "node"

    有了这个和“es2015”模块 tsconfig,我在所有打字稿导入中都需要使用 .JS 扩展名。示例:import { foo } from '../bar.js,否则会引发错误,例如:Error [ERR_MODULE_NOT_FOUND]: Cannot find module D:/...。当然,阻止我使用ts-node-dev 会引发上述错误。

【问题讨论】:

  • 尝试使用 tsc --p ./tsconfig.json 强制编译器加载 tsconfig.json。见docs。如果有帮助,请查看我的项目 here 并观看 package.jsontsconfig.json
  • 我不认为问题在于 TSC 编译器没有加载 tsconfig.json,因为正在编译文件中进行更改。
  • 试试 "target": "es2015""module": "commonjs"
  • 使用目标“es2015”和模块“commonjs”得到相同的错误:“ReferenceError:exports is not defined”
  • 超级奇怪。尝试复制我的 tsconfig.json(见上文)并将其用作您的主要配置文件。也许缺少什么。

标签: javascript typescript tsc ts-node


【解决方案1】:

问题出在ormconfig.js 中,我的实体路径指向.ts 文件而不是.js

解决方案:

entities: ['dist/entity/*.js'],
migrations: ['dist/migration/**/*.js']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    • 2017-05-23
    • 2019-02-12
    • 1970-01-01
    • 2017-06-21
    • 2018-07-22
    相关资源
    最近更新 更多