How to have multiple chunks but a single js file that loads them

1.9k Views Asked by At

I'm trying to setup Webpack, currently not using dev-server and my app is being served by a python backend which has the index.html.

I'm trying to use the SplitChunksPlugin so that I can have multiple chunks (app, vendor, runtime, etc). However, to simplify how it loads from the python backend, I was wondering if there is a way I can tell Webpack to create an extra file, something like main.js which will dynamically load the other chunks in the right order. Is that a thing?

2

There are 2 best solutions below

0
d7my On BEST ANSWER

You can use dynamic import

import(/* webpackChunkName: "chunkName" */ 'chunkPath')

Creating custom chunk and import it when it's needed and your file chunkPath may contain the other chunks you want to split, and it won't be loaded immediately.

from webpack docs:

import('path/to/module') -> Promise

Dynamically load modules. Calls to import() are treated as split points, meaning the requested module and its children are split out into a separate chunk.

0
AudioBubble On

You can use the html plugin to generate a js file that loads all the initial scripts:

      // Generate js entrypoint for the app to be loaded using a script tag
      new HtmlWebpackPlugin({
        alwaysWriteToDisk: true,
        inject: false,
        // If you have multiple entry points and only some should be loaded 
        // this way, list those entry points in the chunks config
        // chunks: ['sdk'],
        filename: '[name].js',
        minify: false,
        templateContent: ({ htmlWebpackPlugin }) => {
          return (
            dedent`
            "use strict";
            (function(m) {     
              var baseUrl = new URL(m.publicPath, document.currentScript.src);        
              m.js.forEach(src => {
                document.head.appendChild(Object.assign(document.createElement('script'), { src: new URL(src, baseUrl).toString() }));
              });
              m.css.forEach(href => {
                document.head.appendChild(Object.assign(document.createElement('link'), { rel: 'stylesheet', href: new URL(href, baseUrl).toString() }));
              });
            ))(
          ` +
            JSON.stringify(htmlWebpackPlugin.files, null, 2) +
            ');'
          );
        },
      }),