在动态 import() 中使用完整 URL [英] Using a full URL in a dynamic import()

查看:54
本文介绍了在动态 import() 中使用完整 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 ES6/Typescript 中的动态 import() 语句中使用完整 URL?

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');
});

出现错误

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

通过 Webpack 和 Typescript,我们已经成功地使用了动态导入的相对路径

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

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

所以看起来 Webpack 已经在运行时进行了模块加载.

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

推荐答案

ES2020 介绍一种新的类似函数的导入语法,所谓的 "动态导入" 允许动态导入 JavaScript 模块.导入过程的精确实现留给主机(例如浏览器或 Node.js),但现代 Web 浏览器确实使用此语法通过 HTTP 实现动态加载,模块使用 URL 标识:

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"

请注意,您需要牢记 CORS 和 MIME 类型的约束.这个 是相关的.

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

这篇关于在动态 import() 中使用完整 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆