Lazily-loaded vendor bundle?

I’m trying to combine the two-explicit-vendor-trunk example with code splitting. But cannot make it to work.

I have two pages (NOT real pages, it’s an SPA using react and react-router):

  • / : needs only vendor.js
  • /d3 : needs both vendor.js and d3.js

The goal is: when visiting /, only app.js and vendor.js are loaded. When the user navigates to /d3, d3.js is loaded as needed. Here is how I try:

webpack config:

entry: { 
  vendor: [ 
    'react',
    'react-dom',
    'react-router',
    ...
  ],
  d3: [ 
    'd3',
  ],
  app: [
      './src/js/index',
  ],
},
plugins: [ 
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    minChunks: Infinity,
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'd3',
    minChunks: Infinity,
    // not sure about the async option here, but without it error occurs
    async: true,
  }),
  ...
],

Router.jsx (I’m using react-router):

export default (
  <Router history={createBrowserHistory()}>
      ...
      <Route path="d3" getComponent={(location, callback) => {
        require.ensure([], (require) => {
          callback(null, require('./pages/D3'));
        });
      }} />
      ...
  </Router>
);

This config doesn’t work as expected since the d3.js bundle is generated but completely ignored by other bundles. And d3.js is also duplicated in chunk 1.1.js. So how can I make this to work? I need this configuration because d3 is too large and slows down initial loading on home page a lot. Furthermore I need to do long-term caching on both vendor.js and d3.js so both must be split out as vendor chunks.

Author: Fantashit

1 thought on “Lazily-loaded vendor bundle?

Comments are closed.