【问题标题】:TypeScript use dynamic import in ES5 with BluebirdTypeScript 在 ES5 中与 Bluebird 一起使用动态导入
【发布时间】:2017-12-22 06:39:32
【问题描述】:

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

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

我可以像消息提示的那样在我的 tsconfig 中包含 ES2015.promise 库,但这会使我失去类型安全性,因为我正在使用 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"]
}

【问题讨论】:

标签: javascript typescript ecmascript-6 promise bluebird


【解决方案1】:

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 实例的构造函数,然后您可以从中构建与在窗口中加载 jquery 时立即获得的相同类型的 jQuery 对象。所以 @987654331 @ 不可访问。)

我正在使用以下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 是处理问题@types/jquery 所必需的。

【讨论】:

  • jquery 模块只是一个示例,我实际上是在浏览器中运行它,所以这不会有问题。但是非常感谢您的工作解决方案!
猜你喜欢
  • 2016-04-09
  • 2019-10-21
  • 2016-08-23
  • 2019-08-27
  • 2015-12-03
  • 1970-01-01
  • 2018-11-19
  • 2016-05-20
相关资源
最近更新 更多