简体   繁体   中英

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

Let's say I manage 2 JavaScript projects both built with Webpack:

  • A Website called User-Website
  • A JavaScript module called External-Module

Note that I'm using 2 separate projets for the same reasons described by the Micro Front end architecture.

I want my User-Website to be able to dynamically load External-Module on demand (using any JavaScript module technology). My User-Website knows at build-time the URL where to reach External-Module .

I can chose whatever technology is needed on both User-Website and External-Module .

I'm looking for a solution:

  • That is easy to implement (maybe JSONP that Webpack already handles to dynamically load chunks?)
  • That doesn't add to much overhead on both User-Website and External-Module (For example JavaScript modules looks good but requires a lot of polyfilling)

My question is related to https://github.com/webpack/webpack/issues/7526


I tried to use JSONP library output on my External-Module but I don't know how to load it in User-Website .

I'm also thinking about using the SystemJS in User-Website to dynamically load External-Module :

  • I could also replace internal JSONP mechanism with SystemJS within Webpack (to save having JSONP mechanism in m bundles).
  • SystemJS looks better and more modern than RequireJS
  • This will require to add SystemJS ( s.js only) overhead.. I'm trying to use less dependencies as possible.

I'm sorry if I did not get the question but I've recently made a project based on the article from the link You've provided. Can't You just host both of the applications and load the part of chunk.js on the runtime ? It's how this particular article's example works. There is an example provided in the article. Some restaurant app with different microfrontends loaded dynamically on the runtime. Isn't it exactly what You need ?

Below code is the 'heart' of this particular example. Take a look.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM