Bare

Summary

Absolute bare minimum necessary to share a React component.

While I would not recommend doing this, you can use React completely without a build step. Doing so results in the absolute most minimal setup possible.

Create a package.json

First, create a package.json file:

{
  "name": "our-library",
  "main": "./index.js",
  "type": "module"
}
  • name (Reference): This is the name of your library that users will use to import it. Here, one would import a component like this:
    import { Button } from 'our-library'
  • main (Reference): All things exported from the file referenced here will be available to import. Here, index.js needs to contain export const Button = ... so that we can do import { Button } from 'our-library'.
  • type (Reference): This tells the importing application what type of JavaScript module to expect. We want to build our libraries as ES Modules, so we set it to "module".

Add react

As we're not going to have a build step for this library, properly setting up React as a dependency doesn't really matter and will be covered in a later setup. For now, we'll just do pnpm add react.

Create a component

Normally, you would create a React component like this:

export const Button = () => (
  <button style={{ backgroundColor: 'steelblue' }}>
    {children}
  </button>
)

For this to work we would need a build step - JSX syntax is not vanilla JavaScript. Instead, our component will look like this:

import { createElement } from 'react'
 
export const Button = ({ children }) => createElement('button', {
  style: { backgroundColor: 'steelblue' }
}, children)

For more information on the createElement method feel free to head over to the React docs.

Publish it

This repo uses a PNPM workspace setup, so we don't need to publish the packages here. Outside of a monorepo, you would use npm publish or some wrapper around it (like np) for this.

Consume it

Within an app, you can now use the button component by importing it like this:

import { Button } from 'our-library'

Button inside our demo app

Our ugly button within our demo app!