Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a full URL in a dynamic import()

Is it possible to use a full URL in a dynamic import() statement in ES6/Typescript?

import('https://foo.com/mymodule.js').then(() => {
    console.log('mymodule is loaded');
});

I get an error

//Cannot find module 'https://foo.com/mymodule.js'.

With Webpack and Typescript, we're already successfully using a relative path with a dynamic import

import(/* webpackChunkName: "mymodule" */ '../mymodule');

so it seems that Webpack already does module loading at runtime.

like image 642
tarling Avatar asked Apr 30 '18 09:04

tarling


Video Answer


1 Answers

ES2020 introduces a new function-like syntax for import, so-called "dynamic imports" permitting the dynamic import of JavaScript modules. The precise implementation of the importing process is left to the host (eg the browser, or Node.js), but modern web browsers do implement dynamic loading over HTTP using this syntax, with the module identified using a URL:

// foo.js at example.com
export function foo() {
    return 'this is foo'
}

// bar.js, running in the client
const { foo } = await import('http://example.com/my-module.js')
foo() // "this is foo"

Note that there are CORS and MIME-type constraints that you need to bear in mind. This and that are relevant.

like image 51
Ben Aston Avatar answered Sep 18 '22 03:09

Ben Aston