DEV Community

loading...
Cover image for Enhanced Code Splitting with Webpack 5

Enhanced Code Splitting with Webpack 5

arxeiss profile image Pavel Kutáč ・2 min read

Webpack 5 is introducing a new feature called Code Splitting, which offers an easier and more customizable way of splitting JS code. However, it is still possible to combine the new method with the Split Chunks plugin.

🇨🇿 V češtině si lze článek přečíst na kutac.cz


Split chunks plugin is very powerful, especially for SPAs. But I made an information system in the old way with HTML templates. I'm using Bootstrap 4, Datatables, EasyMDE, and Magnific popup for historical reasons. I want to load each library only when is really needed. So splitting the whole codebase just into app.js and vendors.js is not satisfying.

Splitting is based on multiple entry points

The main idea of splitting the code is based on multiple entry points with a definition of dependencies. It is basically very easy yet powerful. The code is split just like the developer wants. Each entry point has a name (the key), a path to JS file, and a dependOn attribute specifying the dependency.

As mentioned above, the Split chunks plugin is not removed from Webpack and can be used together with code splitting. A great tutorial is in 4 minutes long video on YouTube.

See the code below with comments inside to get the basic idea of code splitting. More can be found in the documentation.

const path = require('path');

module.exports = {
  entry: {
    // The final file vendors.js contains only jQuery and popper.js
    'public/js/vendors': ['jquery', 'popper.js'],
    // main.js contains all imports like Bootstrap etc...
    // But does not include anything already contained in  vendors.js file, because of dependency
    'public/js/main': {
      import: './resources/assets/js/main.js',
      dependOn: 'public/js/vendors',
    },
    // DataTables are dependant on main.js because of Bootstrap
    // Everything included in main.js or vendors.js will not be included again
    'public/js/datatables': {
      import: './resources/assets/js/datatables.js',
      dependOn: 'public/js/main',
    },
    // Magnific popup needs only jQuery, it is enough to depend on vendors.js only
    'public/js/magnific-popup': {
      import: './resources/assets/js/magnific-popup.js',
      dependOn: 'public/js/vendors',
    },
    // EasyMDE does not contain anything from files above
    'public/js/easymde': './resources/assets/js/easymde.js',
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, './'),
    publicPath: '/',
    ecmaVersion: 5,
  },
};

Discussion

pic
Editor guide