【问题标题】:Using Webpack, how to dynamically load an external module built with another Webpack使用 Webpack,如何动态加载使用另一个 Webpack 构建的外部模块
【发布时间】:2020-02-18 00:59:45
【问题描述】:

假设我管理 2 个使用 Webpack 构建的 JavaScript 项目:

  • 一个名为 User-Website 的网站
  • 一个名为 External-Module 的 JavaScript 模块

请注意,出于Micro Front end 架构中描述的相同原因,我使用了 2 个单独的项目。

我希望我的 User-Website 能够按需动态加载 External-Module(使用任何 JavaScript 模块技术)。我的 User-Website 在构建时知道到达 External-Module 的 URL。

我可以在 User-WebsiteExternal-Module 上选择所需的任何技术。

我正在寻找解决方案:

  • 这很容易实现(也许 Webpack 已经处理 JSONP 以动态加载块?)
  • 这不会增加 User-WebsiteExternal-Module 的开销(例如 JavaScript modules 看起来不错,但需要大量填充)

我的问题与https://github.com/webpack/webpack/issues/7526有关


我尝试在 External-Module 上使用 JSONP 库输出,但我不知道如何在 User-Website 中加载它。

我也在考虑使用User-Website中的SystemJS来动态加载External-Module

  • 我还可以在 Webpack 中用 SystemJS 替换内部 JSONP 机制(以节省在 m 包中包含 JSONP 机制)。
  • SystemJS 看起来比 RequireJS 更好更现代
  • 这将需要添加SystemJS(仅限s.js)开销。我正在尝试使用尽可能少的依赖项。

【问题讨论】:

标签: javascript webpack micro-frontend es6-modules


【解决方案1】:

很抱歉,如果我没有收到问题,但我最近根据您提供的链接中的文章制作了一个项目。 您不能只托管两个应用程序并在运行时加载chunk.js 的一部分吗?这就是这篇特定文章的示例的工作原理。文章中提供了一个示例。一些具有不同微前端的餐厅应用程序在运行时动态加载。这不正是您所需要的吗?

以下代码是这个特定示例的“核心”。看看吧。

componentDidMount() {
    const { name, host } = this.props;
    const scriptId = `micro-frontend-script-${name}`;

    if (document.getElementById(scriptId)) {
      this.renderMicroFrontend();
      return;
    }

    fetch(`${host}/asset-manifest.json`)
      .then(res => res.json())
      .then(manifest => {
        const script = document.createElement('script');
        script.id = scriptId;
        script.src = `${host}${manifest['main.js']}`;
        script.onload = this.renderMicroFrontend;
        document.head.appendChild(script);
      });
  }

【讨论】:

    猜你喜欢
    • 2017-08-22
    • 2020-05-19
    • 2019-11-03
    • 1970-01-01
    • 2018-06-05
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多