Using a full URL in a dynamic import()

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.

Leave a Comment