【发布时间】:2020-07-09 07:37:43
【问题描述】:
我正在运行 Node v14.5.0。我在开发环境中使用ts-node-dev
试图编译成 JS 总是报错。
一开始,我尝试过这个tsconfig:
"target": "es5",
"module": "commonjs"
"outDir": "./dist",
"rootDir": "./src"
但是当我运行 tsc 和 node 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.json 和 tsconfig.json。
-
我不认为问题在于 TSC 编译器没有加载 tsconfig.json,因为正在编译文件中进行更改。
-
试试 "target": "es2015" 和 "module": "commonjs"。
-
使用目标“es2015”和模块“commonjs”得到相同的错误:“ReferenceError:exports is not defined”
-
超级奇怪。尝试复制我的 tsconfig.json(见上文)并将其用作您的主要配置文件。也许缺少什么。
标签: javascript typescript tsc ts-node