Search code examples
webpackwebpack-4

How do you link chunks split by Webpack 4?


The problem

I have a project using Webpack 4 and want to enable code splitting. I have this config to enable split chunks.

  optimization: {
    splitChunks: {
      chunks: 'all'
    },
  }

When I run the build I get some files name:

about-d434910cfbfb3b1f4f52.js
billing-d434910cfbfb3b1f4f52.js
login-d434910cfbfb3b1f4f52.js
vendors~about~billing~login~~97fa390a-d434910cfbfb3b1f4f52.js

about.js, billing.js, and login.js are my entry points. The vendor file contains jQuery which is used on these 3 pages. My understanding is that I need to write 2 script tags in my template like:

<script type="text/javascript" src="http://0.0.0.0:8000/assets/bundles/vendors~about~billing~login~~97fa390a-d434910cfbfb3b1f4f52.js" ></script>
<script type="text/javascript" src="http://0.0.0.0:8000/assets/bundles/about-d434910cfbfb3b1f4f52.js" ></script>

This makes sense but it's not clear to me how I'm supposed to know how to connect which vendor files with which entry point file. In this case there is only one vendor file, but my project has many more dependencies so in reality there may be 3 more. Not to mention these will change as code is changed.

Comparison to Require.js

In Require.js you would do this:

define(['jquery', 'my-module'], function($, myModule) {
  ...
});

and jQuery would be fetched from the server. In Webpack 4 this would be:

import $ from 'jquery';
import MyModule from 'my-module';

But when you do this in Webpack you must list the dependency bundle as a script tag. It will not go and download jQuery when imported.

Webpack dynamic import

I know Webpack has dynamic import which returns a promise:

import('lodash').then(_ => {
    ...
});

This is similar to Require.js, but is meant for segregating application functionality. This is not what I want to do. Perhaps it could work if import() could take multiple module names and I just used that to import everything, but that definitely is not the way this feature is meant to be used according to the docs.

The questions

1) How are you supposed to know programmatically which files depend on which so you can render correct script tags?

2) Is there a way to use import to get the behavior of downloading the module that AMD does when the module is not linked in the page already?


Solution

  • The answer is to use HtmlWebpackPlugin