获取模块内微前端动态加载的模块URL?

发布于 2025-01-16 03:28:21 字数 441 浏览 1 评论 0原文

在移动到“library: { type: "module" }”之前,我们从这里获得了 URL:

const myScript: any = document.currentScript || document.scripts[document.scripts.length - 1];
const baseUrl = new URL(myScript.src).origin + '/';

现在 document.currentScript 为 null 并且 document.scripts 不包含加载的脚本,它们位于某些“webpackChunk{moduleName”中}“ 多变的。

如何从脚本内部加载脚本(模块)的位置?

(import.meta.url给出了脚本的file://地址。我们需要的是导入的模块URL。loadRemoteModule是动态的)

Before to move to "library: { type: "module" }", we have got the URL from here:

const myScript: any = document.currentScript || document.scripts[document.scripts.length - 1];
const baseUrl = new URL(myScript.src).origin + '/';

Now is the document.currentScript null and document.scripts does not contain the loaded scripts and they are in some "webpackChunk{moduleName}" variable.

How to get from where is the script(module) loaded, inside the script?

(import.meta.url gives file:// address of the script. What we need is the imported module URL. loadRemoteModule is dynamic)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

意中人 2025-01-23 03:28:21

我在这里找到了解决方案:
禁用 import.meta.url 的编译时评估

webpack 中有一个新标志。 config.js:

module.exports = {
  module: {
    parser: {
        javascript: {importMeta: false}
    }
  },
  ...
}

现在 import.meta.url 将在运行时评估。抱歉,我已经发布了答案,但是我已经在网上搜索了两天。也许这会为某人节省一些时间。 :)

I have found a solution here:
Disable compile time evaluation of import.meta.url

There is a new flag in webpack.config.js:

module.exports = {
  module: {
    parser: {
        javascript: {importMeta: false}
    }
  },
  ...
}

Now the import.meta.url will be evaluated at runtime. Sorry that I have posted an answer, but I have searched the Internet for two days. May be this will spare some time for someone. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文