How to control shared code sharing with `import ()` chunks (Webpack 2.2)

Using webpack version 2.2.0 .

I have a single page application with one entry config: entry: { app: ['./js/main.js'] } . This is an application that dynamically loads views using import('./js/views/1') to split the code.

The problem I am facing is that the generated generated files are views/1 , views/2 , etc. Contain many duplicate modules. Files and their contents look like this:

  • main: ./js/main.js
    • 0: ./js/views/1.js
    • ./js/modules/a.js
    • ./js/modules/b.js
    • 1: ./js/views/2.js
    • ./js/modules/b.js
    • ./js/modules/c.js

Note that both views/1.js and views/2.js have a complete copy of the common modules/b.js In my case, I have dozens of views and many common modules, so duplication is a big concern to me. This is what webpack-bundle-analyzer looks like:

Bundle analyzer

I tried adding CommonChunkPlugin to help solve this problem, but it doesn't seem to affect dynamic import at all.

What I'm looking for is a way for a web package to automatically move all common modules to separate files. Ideally, I would like webpack to output the following pieces:

  • main: ./js/main.js
    • 0: ./js/views/1.js
    • 1: ./js/views/2.js
    • 2: ./js/modules/a.js
    • 3: ./js/modules/b.js
    • 4: ./js/modules/c.js

Thus, each module is literally a separate block. This would be the most optimal way to download them using HTTP2.

Here is the code for an example project: https://github.com/EvNaverniouk/webpack-code-splitting

How can I achieve this?

I believe this is due to this problem: https://github.com/webpack/webpack/issues/3981

+8
source share
2 answers

To solve the duplication problem, you can use the CommonsChunkPlugin provided by the webpack optimization package. documentation , he does the following:

Create an extra piece that contains common modules shared between entry points.

Regarding the second issue you are describing, this will be the task for gulp. Gulp accepts an input stream and outputs this stream to a file. Basically creating a 1-on-1 copy of the original, but then transferred, compiled, etc.

I would not recommend the second structure for the Internet, as it creates so many HTTP requests for the browser that it can take quite a while. Especially if you are working on a website using the HTTP / 1.1 protocol. It is usually more beneficial to allow the client to upload fewer files with more content in them.

0
source

In web packet 4, I think you need to set minSize to 0. The web packet will duplicate this code if it is considered that it will save an HTTP request. Setting minsize to 0 makes it split.

 optimization: { splitChunks: { chunks: "all", minSize: 0 } } 
0
source

Source: https://habr.com/ru/post/1014039/


All Articles