Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bundle in Webpack assets in multiple pages that don't link to every other assets?

There is something I couldn't understand about Webpack.

Most of the webpack examples show a main entry point app.js which imports all other react components for Webpack to recursively build a resultant file. If there were multiple entry points, like pageA.js and pageB.js, we put them into an array in the entry argument.

My problem however is that my "main" entry point doesn't use and import every single components. Maybe just some. On PageA, I might only import ComponentA and ComponentB. On PageB, I might only import ComponentB and ComponentC. Then in the main.js on my MainPage, I might only import ComponentD.

I can put main.js, PageA and PageB all into my entry points. But does that mean I have to add to the entry list in webpack config every time I have a new page?

How should I approach this scenario using Webpack?

like image 778
Carven Avatar asked Jun 28 '16 23:06

Carven


People also ask

What is chunking in webpack?

Chunk: This webpack-specific term is used internally to manage the bundling process. Bundles are composed out of chunks, of which there are several types (e.g. entry and child).

How do I bundle files in webpack?

You can bundle your JavaScript using the CLI command by providing an entry file and output path. Webpack will automatically resolve all dependencies from import and require and bundle them into a single output together with your app's script. But that's just the bare minimum it can do.

Can you have multiple entry points in a single webpack configuration file?

webpack.config.jsWe can also pass an array of file paths to the entry property which creates what is known as a "multi-main entry". This is useful when you would like to inject multiple dependent files together and graph their dependencies into one "chunk".


1 Answers

Sounds like your setup is a typical webpack multi-page app, which is usually consist of common/vendor bundle (entry point), and separate bundles (entry points) for each page, like your PageA and PageB.

For each page you will need to include the common/vendor bundle first, and then include the page specific bundle.

<script src="common.js">
<script src="PageA.js">

Have a look at multiple-entry-points and multiple-commons-chunks. Webpack can automatically extract the common deps and bundle them together (1st example), or you can specify which deps should go into which common chucks (2nd example). Also have a look at common-chunk-and-vendor-chunk, which perfectly explained how common chuck works.

According to your description, your setup is very similar to the first example (multiple-entry-points).

And yes, you will probably need to add a new entry when you have a new page, like PageC.

like image 185
waltzofpearls Avatar answered Oct 04 '22 06:10

waltzofpearls