Preventing Duplication by “Splitting” Shared Code into Separate Files

Preventing Duplication by “Splitting” Shared Code into Separate Files

Suppose you have multiple entry files and each requires jquery. In this case, each output file will contain jQuery, making your files much larger than necessary. To solve this, you can ask webpack to analyze your files and split them into additional files, which will contain “shared” code.

To enable this, call splitEntryChunks():

  1. // webpack.config.js
  2. Encore
  3. // ...
  4. // multiple entry files, which probably import the same code
  5. .addEntry('app', './assets/js/app.js')
  6. .addEntry('homepage', './assets/js/homepage.js')
  7. .addEntry('blog', './assets/js/blog.js')
  8. .addEntry('store', './assets/js/store.js')
  9. + .splitEntryChunks()

Now, each output file (e.g. homepage.js) may be split into multiple file (e.g. homepage.js, vendor~homepage.js). This means that you may need to include multiple script tags (or link tags for CSS) in your template. Encore creates an entrypoints.json file that lists exactly which CSS and JavaScript files are needed for each entry.

If you’re using the encore_entry_link_tags() and encore_entry_script_tags() Twig functions from WebpackEncoreBundle, you don’t need to do anything else! These functions automatically read this file and render as many script or link tags as needed:

  1. {#
  2. May now render multiple script tags:
  3. <script src="/build/runtime.js"></script>
  4. <script src="/build/vendor~homepage.js"></script>
  5. <script src="/build/homepage.js"></script>
  6. #}
  7. {{ encore_entry_script_tags('homepage') }}

Controlling how Assets are Split

The logic for when and how to split the files is controlled by the SplitChunksPlugin from Webpack. You can control the configuration passed to this plugin with the configureSplitChunks() function:

  1. // webpack.config.js
  2. Encore
  3. // ...
  4. .splitEntryChunks()
  5. + .configureSplitChunks(function(splitChunks) {
  6. + // change the configuration
  7. + splitChunks.minSize = 0;
  8. + })

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.