TypeScript在ES5中使用Bluebird进行动态导入

时间:2017-07-17 16:19:42

标签: javascript typescript ecmascript-6 promise bluebird

我正在尝试在TypeScript中使用新的动态import()函数,但是我收到以下错误:

  

TS2712: ES5 / ES3中的动态导入调用需要“承诺”   构造函数。确保你有一个'承诺'的声明   构造函数或在--lib选项中包含“ES2015”。

我可以在我的tsconfig中包含ES2015.promise lib,就像消息所示,但这会让我失去类型安全,因为我正在使用Bluebird的承诺。

我知道可以在TypeScript中使用Bluebird作为async/await,所以我认为这也应该以相同的方式工作。

该消息还提到了这一点:

  

确保您拥有'Promise'构造函数或[...]

的声明

是否可以声明Bluebird构造函数在TS中用作Promise构造函数?

示例代码:

import * as Bluebird from 'bluebird';

// This works
async function exampleAsync(): Bluebird<number> {
    const result = await Bluebird.resolve(5);
    return result;
}

// This does not
import('jquery').then($ => {
    console.log($.fn.jquery);
});

TSConfig:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "removeComments": true,
    "sourceMap": true,
    "alwaysStrict": true,
    "forceConsistentCasingInFileNames": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "strictNullChecks": true,
    "allowJs": true,
    "typeRoots": ["node_modules/@types"],
    "lib": ["es5", "dom", "es2015.collection"]
  },
  "exclude": ["node_modules"]
}

1 个答案:

答案 0 :(得分:4)

TypeScript正在寻找全球 Promise。您在代码中拥有的是在模块中声明的Promise(“bluebird”),并在另一个模块中本地使用。

这是解决编译错误并获得可运行代码的最小方法:

test.ts

import * as Bluebird from 'bluebird';

declare global {
    const Promise: {
        new <R>(callback: (
            resolve: (thenableOrResult?: R | PromiseLike<R>) => void,
            reject: (error?: any) => void,
            onCancel?: (callback: () => void) => void
        ) => void): Bluebird<R>;
    };
}

import('jquery').then($ => {
    console.log($);
});

我已将console.log语句修改为仅输出$,以便上面的代码可以在Node中轻松运行而不需要浏览器。 (当您在Node中加载jquery时,您将获得一个需要Window实例的构造函数,然后您可以在该实例中构建加载{{1}时立即获得的相同类型的jQuery对象在一个窗口中。所以jquery无法访问。)

我正在使用以下来自您的$.fn.jquery

tsconfig.json

您有几个不必要的选项,{ "compilerOptions": { "module": "commonjs", "target": "es5", "removeComments": true, "sourceMap": true, "alwaysStrict": true, "forceConsistentCasingInFileNames": true, "noUnusedLocals": true, "noUnusedParameters": true, "strictNullChecks": true, "allowJs": true, "skipLibCheck": true, "lib": ["es5", "dom", "es2015.collection"] } } 是处理问题skipLibCheck所必需的。