Skip to content

Instantly share code, notes, and snippets.

@darrenjaworski
Last active August 10, 2018 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darrenjaworski/958eccc5a5fadf24ebc871fde0e9dc03 to your computer and use it in GitHub Desktop.
Save darrenjaworski/958eccc5a5fadf24ebc871fde0e9dc03 to your computer and use it in GitHub Desktop.
Convert create react app to a component library...

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