打字稿使用ES5动态导入与蓝鸟

问题描述:

我试图使用打字稿新的动态import()功能,但我得到了以下错误:打字稿使用ES5动态导入与蓝鸟

TS2712: A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your --lib option.

我可能包括ES2015.promise LIB我tsconfig像消息表明,但这会让我失去类型安全性,因为我使用蓝鸟承诺。

我知道在TypeScript中可以使用蓝鸟async/await,所以我想这也应该以同样的方式工作。


该消息也提到了这一点:

Make sure you have a declaration for the 'Promise' constructor or [...]

是否有可能宣布蓝鸟构造被用作TS无极构造?


示例代码:

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"] 
} 
+0

https://stackoverflow.com/questions/45171651/typescript-promise-constructor-declaration – lilezek

打字稿正在寻找一个全球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中运行,而不需要浏览器。 (当加载在节点jquery,你需要一个Window实例,从中再建同类型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需要处理的问题@types/jquery

+0

'jquery'模块只是一个例子,我实际上在浏览器中运行它,这样就没有问题了。但非常感谢工作解决方案! –