Skip to content

Instantly share code, notes, and snippets.

@vijaydeepak-tt
Created November 16, 2022 05:12
Show Gist options
  • Save vijaydeepak-tt/9c366e500fc3d733e963938f645bd89e to your computer and use it in GitHub Desktop.
Save vijaydeepak-tt/9c366e500fc3d733e963938f645bd89e to your computer and use it in GitHub Desktop.

Use CRA to get you going.

$ npx create-react-app component-library

You're going to want styleguidist. Follow the instructions here.

Add .babelrc file to the root of your library.

{
  "presets": ["react-app"]
}

Modify your package.json.

{
  "main": "dist/index.js",
  "scripts": {
    "build": "rm -rf dist && NODE_ENV=production babel src --out-dir dist --copy-files --ignore __tests__,spec.js,test.js,__snapshots__,*.md",
  }
}

This basically builds and moves your components to a dist folder for publishing. We are also registering your entry point into the application as 'dist/index.js'.

You can remove App.js since we won't be using it in the library. Create a 'components' folder inside 'src'. Create any subsequent components in their own folder inside components.

  • src
    • components
      • button
      • card
      • blah

In 'src/index.js' you'll want to export your components as this is now your main script.

import "./global.css";

export { default as Card } from "./components/card";
export { default as Button } from "./components/button";

Write your tests and components at an atomic level.

To build the library run:

$ npm run build

Finished? Ready to publish? Let's test it locally first...

Within the project folder run the following command:

$ npm link

In the project you're wanting to utilize your newly minted component library run:

$ npm link component-library

Replace 'component-library' with whatever you list on your package.json as the name of the library.

This will create a symlink locally from your library to the node_modules folder of the project that is utilizing the component library. Get your app up and running and then import your components from your component library.

import { Button } from 'component-library';

// in your render function
render() {
  return <Button />
}

Pretty neat.

Publish it to the world using:

$ npm publish
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment