Search code examples
reactjssasscreate-react-appnpm-installnpm-publish

Customisable component library in ReactJS


I'm trying to create a customisable ReactJS component library. I've considered create-react-library for the purpose. Component development is almost finished. I've placed all my components in separate directories, and I'm exporting all of them in one go, with the help of an index.js. All components have associated local scss files as well. These component level scss file takes reference from another variables.scss which has scss variables like,

$primaryColor: #ff0000;

$secondaryColor: #000000;

There are 2 parts to this question.

  1. Is there any way to not compile the scss into one css when we publish the package. Currently create-react-library is compiling all the scss into a folder named dist as index.css, which doesn't give the option to update styles from parent project with scss variables.

  2. Once the issue with scss compilation is solved, how can we update these variables from a parent project (where developers will be using the package created).

Any sort of help is much appreciated.


Solution

  • At last after days of research I was able to resolve this. Posting the solution so that somebody might get benefited.

    Is there any way to not compile the scss into one css when we publish the package. Currently create-react-library is compiling all the scss into a folder named dist as index.css, which doesn't give the option to update styles from parent project with scss variables.

    For bundling, microbundle was provided out of the box with create-react-library. I moved that to rollup which gives a lot of options for bundling. Then I used rollup-plugin-copy to simply copy my components (ofcourse without compilation) to the dist folder.

      plugins: [
        copy({
          targets: [
            { src: 'src/assets/**/*', dest: 'dist' },
            {
              src: ['src/components/**/*', '!**/*.spec.*'],
              dest: 'dist',
            },
          ],
          verbose: true,
          flatten: false,
        })
       ]

    Once the issue with scss compilation is solved, how can we update these variables from a parent project (where developers will be using the package created).

    As you can see, from my above piece of code snippet, I'm copying the associated assets (theme css and even components) to my dist folder. For my purpose, it was more than enough. All that I need to do is, import the scss files (to the bottom of an index.scss. This is important as scss variables that need to override should be loaded even before the styles are loaded from node_modules) that I have to the consumer application. Please have a look at sass default values for variables to get an understanding of how one can update the scss variables from consumer application.