2

I am trying to reduce bundle size of my nextjs project and I have some problem with tree shaking. Let me explain. I have a Flags.js file that export multiple flags component :

export { default as FlagsCn } from './FlagsCn';
export { default as FlagsDe } from './FlagsDe';
export { default as FlagsEsCt } from './FlagsEsCt';
export { default as FlagsEs } from './FlagsEs';
export { default as FlagsFr } from './FlagsFr';
export { default as FlagsGb } from './FlagsGb';
export { default as FlagsGr } from './FlagsGr';
export { default as FlagsIt } from './FlagsIt';
export { default as FlagsJp } from './FlagsJp';
export { default as FlagsNo } from './FlagsNo';
export { default as FlagsPh } from './FlagsPh';
export { default as FlagsPt } from './FlagsPt';
export { default as FlagsRu } from './FlagsRu';
export { default as FlagsTh } from './FlagsTh';
export { default as FlagsBg } from './FlagsBg';

Then I import only two flags into my other component :

import { FlagsFr, FlagsGb } from '@components/Flags';

But I noticed that all Flags are imported when I take a look into the bundle with webpack-bundle-analyzer. If I apply sideEffects to false into the package.json, the js bundle file size reduce by 400kb but I've got some strange error during the navigation. I think it means that some library are causing side effects.

So what should I do ? Thanks for you help :)

  • Visit all the modules that were dropped and inspect their top-level statements? – Bergi Oct 09 '19 at 11:41
  • You need to find out what code has side effects and supply an array to sideEffects which lists those modules. see the [webpack docs](https://webpack.js.org/guides/tree-shaking/) for more info – Euan Smith Oct 10 '19 at 14:40

1 Answers1

0

A possible reason could be that you have not set mode: 'production' in webpack.config.js.

Additionally, if you don't need all the flags simultaneously then consider code splitting. It can be done by:

winwiz1
  • 2,906
  • 11
  • 24
  • You suggest "multiple Reat SPAs" - React is not referenced anywhere in the question. – Euan Smith Oct 09 '19 at 11:35
  • @EuanSmith True. This particular suggestion in based on assumption that React is used and can be safely ignored if it is not. – winwiz1 Oct 09 '19 at 11:40
  • Thanks for you reply @winwiz1 ! Production mode is correctly set and flags are not used in the project for now so I don't need them into the final bundle, even if they are in seperate js file with dynamic import. Between I'm using nextjs/babel/react. Babel doesn't have any commonjs transform plugin set also (I know that it can break tree-shaking – Lucien Peslier Oct 10 '19 at 09:31