【发布时间】:2017-07-21 08:37:42
【问题描述】:
我有一个 nodeJS-Express-Typescript 项目,我想在其中使用一些带有 async/await 的原生 Promise 以及一些函数的默认值。这将是我可以实现的一个简单示例:
sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, 500));
}
async someFunction(param = "default") {
doStuff(param);
await sleep(500);
doSomeMoreStuff();
}
IDE 警告我这个错误:
$ tsc -p .
error TS2468: Cannot find global value 'Promise'.
spec/routes/users.spec.ts(508,23): error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.
src/utils/sleep.ts(10,20): error TS2693: 'Promise' only refers to a type, but is being used as a value here.
所以我必须在我的tsconfig.json 中添加 es2015 作为目标:
"target": "es2015"
但是,执行转译后的 JS 时出现此错误:
/../users-api/dist/src/repository/realm-helper.js:21
static init(development = false) {
^
SyntaxError: Unexpected token =
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/../users-api/dist/src/routes/users.js:4:24)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
所以我必须将目标更改为“es5”:
"target": "es5"
这会导致恶性循环。
我试过改变“target”和“module”的值,但总是失败。
我在这里遗漏了什么吗?理论上,typescript 2.2 支持这两个功能,所以我不明白为什么我不能转译。
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"rootDir": ".",
"sourceMap": true,
"module": "commonjs",
"target": "es5"
},
"include": [
"./src/**/*",
"./spec/**/*"
]
}
打字稿 2.4.1
节点 4.4.7
【问题讨论】:
标签: node.js typescript