Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tree-shaking with rollup

I have a project in which I bundle a components library using Rollup (generating a bundle.esm.js file). These components are then used in another project, that generates web pages which use these components - each page is using different components. The problem is, that the entire components library is always bundled with the different page bundles, regardless of which components I'm using, unnecessarily increasing the bundle size.

This is my Rollup setup:

import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import pkg from './package.json';

const extensions = [
  '.js', '.jsx', '.ts', '.tsx',
];
export default [
  {
    input: './src/base/index.ts',
    plugins: [
      peerDepsExternal(),
      resolve({ extensions }),
      babel({
        exclude: 'node_modules/**',
        extensions,
      }),
      commonjs(),
    ],
    output: [
      { file: pkg.main, format: 'cjs', sourcemap: true },
      { file: pkg.module, format: 'es', sourcemap: true },
    ],
    watch: {
      clearScreen: false,
    },
  },
];

I have "modules" set to false in webpack, as well.

like image 361
Luoruize Avatar asked Mar 25 '19 13:03

Luoruize


People also ask

What is tree-shaking concept?

Tree shaking is a term commonly used within a JavaScript context to describe the removal of dead code. It relies on the import and export statements to detect if code modules are exported and imported for use between JavaScript files.

Does Babel do tree-shaking?

Babel is an indispensable tool, but it may make the effects of tree shaking a bit more difficult to observe.

What is Rollupjs?

Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application. It uses the new standardized format for code modules included in the ES6 revision of JavaScript, instead of previous idiosyncratic solutions such as CommonJS and AMD.


1 Answers

There are things you will need to do to achieve treeshakable code from both sides - the built package and the project using it.

From your code snippet, I see that you have not add flag preserveModules: true in the rollup config file to prevent the build output from bundling. Webpack can not treeshake a bundled file FYI.

export default {
  ...
  preserveModules: true,
  ...
}

On the side of the project that using it, you have to specify sideEffects in the package.json - read the doc to know how to config them. Beside that, the optimization in webpack has to has sideEffects: true, also read the doc here.

Hope this helps!

like image 126
Phạm Huy Phát Avatar answered Oct 21 '22 16:10

Phạm Huy Phát