2

I tried to add

  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all'
        }
      }
    }
  },

To my webpack config file but when I compare the network when loading the pack in incognito, with and without that config, both are identical.

Also running a build yield the same output.

Is there another way to know for sure if it does something?

What I want to achieve is that each page on my site will have its own chunk, and only that will be loaded when that page is navigated to.

Roman Pokrovskij
  • 9,449
  • 21
  • 87
  • 142
shinzou
  • 5,850
  • 10
  • 60
  • 124

1 Answers1

1

Well, to separate each chunk per page, you should use "Dynamic import", which is a technique of code splitting. By using it, you explicitly say to webpack that you don't need it, up to the point that it is required.

What it does? It is a "wrapper" that is turned into require.ensure, which returns a promise. And because it is a promise, it can be requested down the road.

To do that, you: import("path/to/whatever");. If you want to do something, for example, in react.

import("component").then((c) => return <c />);

PlayMa256
  • 6,603
  • 2
  • 34
  • 54
  • So I'll have to update all (or most) of the imports in my project in all the files? from `import x from 'y; import z from 'w'';` to import `import("x").import(y).then((c) => ...`? It seems like callback hell. Also, it doesn't seem like a ES6/React way to wrap every class or component with a promise... – shinzou Aug 07 '18 at 16:12
  • That was just an example, obviously there any many other ways to do that. Look for lazy-load routes or code splitting route level. That can be achieved using `react-loadable` or something like that. But yeah, in theory you would have to change all of the imports, if you really need. – PlayMa256 Aug 07 '18 at 16:14
  • I know it's starting to get off topic but how do you use react-loadable with routes and containers? I'll probably just ask another question. – shinzou Aug 08 '18 at 11:12
  • Check out [Paragons](https://www.npmjs.com/package/generator-paragons) It is using react-loadable with SSR. – Dan Aug 09 '18 at 14:56