0

我正在使用使用“ts-node”运行的 Typescript 项目。

$ ts-node .\src\index.ts
it works =)

但我想将其编译为 Javascript。所以我跑了。

$ tsc
$ node .\src\index.js

但我得到了休闲错误:

(node:4392) UnhandledPromiseRejectionWarning: \event-monitor\src\models\Alarm.ts:1
(function (exports, require, module, __filename, __dirname) { import BaseEntity from "./BaseEntity";
                                                                     ^^^^^^^^^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:657:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
(node:4392) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:4392) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我不明白为什么使用 ts-node 运行良好,但使用 TSC 它不起作用。

这是我的 ts-config 文件

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "strictNullChecks": false,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "baseUrl": ".",
    "sourceMap": true,
    "outDir": "dist",
    "noImplicitAny": false,
    "strictPropertyInitialization": false,
    "emitDecoratorMetadata": true,
    "types": ["mocha", "chai", "node"],
    "paths": { "@/*": ["src/*"] },
    "lib": ["es5", "es6"]
  },
  "include": ["src/**/*.ts", "tests/**/*.ts", "repoTest.ts"],
  "exclude": ["node_modules"]
}

我正在使用的模块:

"lodash": "^4.17.11",
"mysql": "^2.17.1",
"reflect-metadata": "^0.1.13",
"restify": "^8.3.0",
"sqlite3": "^4.0.6",
"typeorm": "^0.2.16",
"typescript": "^3.0.3"
4

2 回答 2

0

Node 不支持 ES6 模块,因此您需要使用 CommonJS 模块的特殊 TyeScript 格式导入和导出模块,例如

export = BaseEntity;

import BaseEntity = require('./BaseEntity');

这在TS 手册中有记录(不是很好)

于 2019-04-29T14:10:17.950 回答
0

我才弄清楚会发生什么。

我使用的是 TypeORM,它正在为其实体寻找 TS 文件。

但是在“js 模式”中,我必须配置 TypeOMR 来代替查看 dist/js 文件。

于 2019-09-27T13:37:23.960 回答