简体   繁体   中英

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?

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.

Webpack's config is actually a JS module. This means that the object you return can be built programmatically rather than manually.

What you want is for webpack to handle chunks optimization properly for you . This, along with programmatically determining the pages you have, should allow you to generate all your assets.

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