How to Tree shake @carbon/charts-react?

59 views Asked by At

I am building a react component lib, this lib has @carbon/charts-react as dependency.

in one of the component I am importing RadarChart from @carbon/chars-react and this the only component from @carbon/charts-react that I am using in lib.

import { RadarChart as RadarChartCarbon } from '@carbon/charts-react';

the problem:

when I run rollup to build the lib I noticed the whole @carbon/charts-react is included in the build.

Ho to include only the RadarChart component in build? Thanks in advance.

here is rollup config:

export default {
  input: 'src/index.js',
  output: [
    {
      format: 'es',
      dir: 'build',
      // preserveModules: true,
      // preserveModulesRoot: 'src',
      // sourcemap: false,
    },
  ],

  plugins: [
    peerDepsExternal(),
    typescript({
      module: 'ESNext',
      declarationDir: './build',
    }),
    commonjs({
      include: 'node_modules/**',
      namedExports: {
        'react-is': ['isForwardRef', 'isValidElementType'],
      },
    }),
    resolve({
      preferBuiltins: true,
    }),
    babel({
      babelHelpers: 'runtime',
      exclude: 'node_modules/**',
      presets: ['@babel/preset-react'],
      plugins: [['@babel/plugin-transform-runtime', { useESModules: true }]],
    }),
    postcss({
      to: './build/base.css',
      preprocessor: (content, id) =>
        new Promise(res => {
          const result = sass.renderSync({ file: id });

          res({ code: result.css.toString() });
        }),
      plugins: [url(options), autoprefixer],
      modules: {
        scopeBehaviour: 'global',
      },
      extract: 'base.css',
      use: [
        [
          'sass',
          {
            includePaths: ['./node_modules'],
          },
        ],
      ],
    }),
    json(),
    terser(),
    del({ targets: 'build/*' }),
    visualizer({
      open: true,
    }),
  ],
};

RadarChart

enter image description here

1

There are 1 answers

0
ArrayConstructor On BEST ANSWER

Sadly the library @carbon/charts-react isn't tree-shakable.

screen

(tested with agadoo)

So however you import as long as it is from index.js it will take everything in the final bundle.

What you can do is import like that:

  import RadarChartCarbon from 'Relative/path/to/node_modules/@carbon/charts-react/dist/charts/RadarChart';

This way, you will only take the chart you want in your final bundle.

Hope it helps you ! :)