4

I currently wanted to optimize handling modules on my application with the implemenation below described. I'm not sure why the page final bundle size increased. It only kept the same bundle size adding on the package.json the flag sideEffects: false

Does Nextjs treeshake modules out-of-the-box?

Module code

// file ModuleA.js
import React from 'react';
const ModuleA = props => (
  // some code
);
export default ModuleA;

// file ModuleB.js
import React from 'react';
const ModuleB = props => (
  // some code
);

export default ModuleB;

Page code

import ModuleA from '~/ModuleA';
import ModuleB from '~/ModuleB';

// Page size production build 25KB


Optimized module handling

// modules/index.js
export { default as ModuleA } from './ModuleA';
export { default as ModuleB } from './ModuleB';
export { default as ModuleC } from './ModuleC';
export { default as ModuleD } from './ModuleD';

Page code

import {
  ModuleA,
  ModuleB,
} from '~/modules';

// without sideEffects: false - production build 50KB
// with sideEffects: false - production build 25KB

Ion
  • 1,262
  • 12
  • 19
  • 2
    What is your question again? Does Next.js treeshake modules out-of-the-box? Yes, it does. In your examples everything works as intended. "Optimized module handling" is called barrel file and it is actually not very good practice, in my opinion, because it messes up with tree shanking. – Danila Jul 22 '21 at 15:35
  • When you say "it messes up with tree shaking" do you mean it does not tree shake the barrel file? Looking at the documentation of sideEffects on treeshaking https://webpack.js.org/guides/tree-shaking/#clarifying-tree-shaking-and-sideeffects they have a similar example of a barrel file components/index.js. Is that a different cenario? – Ion Jul 22 '21 at 16:31
  • 5
    @Ion Yes, tree shaking doesn't work properly on using barrel files (in Next.js). Refer this issue: https://github.com/vercel/next.js/issues/12557 – brc-dd Jul 22 '21 at 16:58

0 Answers0