[英]Typescript not compiling correctly to commonjs/es2015
I'm running Node v14.5.0.我正在运行 Node v14.5.0。 I'm using
ts-node-dev
in dev enviroment我在开发环境中使用
ts-node-dev
Trying to compile to JS always gives an error.尝试编译为 JS 总是会出错。
At first, I tried with this tsconfig
:起初,我尝试使用这个
tsconfig
:
"target": "es5",
"module": "commonjs"
"outDir": "./dist",
"rootDir": "./src"
But when I run tsc
and node dist/app.js
I get the following error:但是当我运行
tsc
和node dist/app.js
时,我收到以下错误:
UnhandledPromiseRejectionWarning: D:\Dev\src\entity\BaseEntity.ts:1
import {
^^^^^^
SyntaxError: Cannot use import statement outside a module
After doing some research, I found that I should tell Node to use Modules adding "type": "module"
to package.json
.经过一番研究,我发现我应该告诉 Node 使用 Modules 添加
"type": "module"
到package.json
。 After that, the error changed to:之后,错误变为:
Object.defineProperty(exports, "__esModule", { value: true });
^
ReferenceError: exports is not defined
Doing some more research I tried several different things like:做了更多的研究,我尝试了几种不同的方法,例如:
Changing tsconfig
from "module": "commonjs"
to "module": "es2015"
将
tsconfig
从"module": "commonjs"
更改为"module": "es2015"
This also causes to be unable to run ts-node-dev
.这也会导致无法运行
ts-node-dev
。 It throws the error: Cannot use import statement outside a module
.它抛出错误:
Cannot use import statement outside a module
。
Adding to tsconfig
"moduleResolution": "node"
添加到
tsconfig
"moduleResolution": "node"
With this and "es2015" module tsconfig I'm requered in all my typescript imports to use the.JS extension.有了这个和“es2015”模块 tsconfig,我在所有 typescript 导入中都需要使用 .JS 扩展名。 Example:
import { foo } from '../bar.js
, otherwise throws an error like: Error [ERR_MODULE_NOT_FOUND]: Cannot find module D:/...
.示例:
import { foo } from '../bar.js
,否则会引发类似错误: Error [ERR_MODULE_NOT_FOUND]: Cannot find module D:/...
。 And of course, prevents me from using ts-node-dev
as throws an error described above.当然,阻止我使用
ts-node-dev
会引发上述错误。
The problem was in the ormconfig.js
where my entities path was pointing to a .ts
file instead of a .js
.问题出在
ormconfig.js
中,我的实体路径指向.ts
文件而不是.js
。
Solution:解决方案:
entities: ['dist/entity/*.js'],
migrations: ['dist/migration/**/*.js']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.