Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

typescript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...