Using Rollup for a React Component Library

I am beginning to learn a bit about bundling as I am working on updating a small, internal React component library which uses Rollup.

Current State

Right now, all of the components are being bundled down into one index.js files. And whenever I import one or multiple...

import { Button, Input } from 'my-library';

...the entire library is being imported. I would like to fix that.

At this point, I have updated Rollup to create named component files so I can do imports like this:

import Button from 'my-library/Button';

That is fine when I am using just one component but whenever I need more than one, it feels redundant to have to have, for example, five lines of imports from the same library. But whenever I again try to destructure them, the entire library is imported.

The Goal

I would like to have the ability to run that same destructured import statement from above but only import those two components.

rollup.config

export default {
  experimentalCodeSplitting: true,
  input: [
    'src/index.js',
    'src/components/Button/Button.js',
    'src/components/Input/Input.js',
  ],
  output: {
    exports: 'named',
    dir: 'dist/',
    format: 'cjs',
    chunkFileNames: 'chunks/[name]-[hash].js',
  },
  plugins: [
    external(),
    babel({ exclude: 'node_modules/**', plugins: ['external-helpers'] }),
    resolve(),
    commonjs(),
  ],
};

index.js

import Button from './components/Button/Button';
import Input from './components/Input/Input';

exports.Button = Button;
exports.Input = Input;

So this results in two files, Button.js and Input.js being built for each component which is great. But is it possible to bring in both components without the rest of the library in one import statement?

Notes

  • The library currently uses Rollup but I don't think we need it if there's an easier solution.

  • I feel like using the experimentalCodeSplitting feature isn't the ideal solution for this and I don't really like having the chunk files.

Thanks for helping out!

Answers:

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.