簡體   English   中英

使用Webpack,如何動態加載使用另一個Webpack構建的外部模塊

[英]Using Webpack, how to dynamically load an external module built with another Webpack

假設我管理着 2 個使用 Webpack 構建的 JavaScript 項目:

  • 一個名為User-Web 的網站
  • 一個名為External-Module 的JavaScript模塊

請注意,出於與微前端架構所述相同的原因,我使用了 2 個單獨的項目。

我希望我的用戶網站能夠按需動態加載外部模塊(使用任何 JavaScript 模塊技術)。 我的用戶網站在構建時知道到達External-Module的 URL。

我可以選擇User-WebsiteExternal-Module上需要的任何技術。

我正在尋找解決方案:

  • 這很容易實現(也許 Webpack 已經處理了動態加載塊的 JSONP?)
  • 這不會給用戶網站外部模塊增加太多開銷(例如JavaScript 模塊看起來不錯,但需要大量的 polyfilling)

我的問題與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 )開銷。我正在嘗試使用盡可能少的依賴項。

如果我沒有得到這個問題,我很抱歉,但我最近根據你提供的鏈接中的文章做了一個項目。 你不能只托管兩個應用程序並在運行時加載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);
      });
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM