Skip to content Skip to sidebar Skip to footer

Typescript Use Dynamic Import In Es5 With Bluebird

I'm trying to use the new dynamic import() function in TypeScript, but I get the following error: TS2712: A dynamic import call in ES5/ES3 requires the 'Promise' constructor. M

Solution 1:

TypeScript is looking for a globalPromise. What you have in your code is a Promise declared in a module ("bluebird") and used locally in another module.

Here's a minimal way to get the compilation errors to be resolve and to have runnable code:

test.ts:

import * asBluebirdfrom'bluebird';

declareglobal {
    constPromise: {
        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($);
});

I've modified the console.log statement to just output $ so that the code above can be readily run in Node rather than require a browser. (When you load jquery in Node, you get a constructor that needs a Window instance from which you then build the same kind of jQuery object you immediately get when you load jquery in a window. So $.fn.jquery is not accessible.)

I'm using the following tsconfig.json which I derived from yours:

{"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"]}}

You had a couple unnecessary options in there, and skipLibCheck is necessary to handle issues @types/jquery.

Post a Comment for "Typescript Use Dynamic Import In Es5 With Bluebird"