DEV Community

ynwd
ynwd

Posted on

How to integrate storybook with npm workspace, react, and webpack

Storybook is the most popular UI component development tool for React. It helps you develop and design UI components outside your app in an isolated environment.

This is the very basic setup to integrate our previous react monorepo with storybook. You can find the source code of this tutorial on monorepo-storybook-branch.

Setup Storybook

You can use this repo to start.

cd web/components/
Enter fullscreen mode Exit fullscreen mode

Install storybook

npx sb init --builder webpack5 -f
Enter fullscreen mode Exit fullscreen mode

You can find detail overview of storybook and webpack 5 on this page: Storybook for Webpack 5

Run storybook

npm run storybook
Enter fullscreen mode Exit fullscreen mode

You can also run storybook from the app root folder

npm run storybook -w @fstr/components
Enter fullscreen mode Exit fullscreen mode

Update webpack config

This update is used to handle css files of storybooks.

const path = require("path")

module.exports = {
    mode: "production",
    entry: {
        index: { import: "./src/index.js" }
    },
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: "babel-loader",
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            },
        ],
    },
    output: {
        filename: "components.bundle.min.js",
        library: 'fstrComponents',
        libraryTarget: 'umd',
        clean: true
    },
}
Enter fullscreen mode Exit fullscreen mode

You can find detail instruction to setup webpack css on this page

Use storybook component

Update index

// web/components/src/index.js
import React from "react"
import { Button } from "./stories/Button.jsx"

const Header = ({ text = "" }) => {
    return (
        <h1>Shared header library {text}</h1>
    )
}

export {
    Button,
    Header
}
Enter fullscreen mode Exit fullscreen mode

Still in web/components folder, build the storybook component.

npm run build
Enter fullscreen mode Exit fullscreen mode

You can also build from root folder.

npm run build -w @fstr/components
Enter fullscreen mode Exit fullscreen mode

Link the built components to npm workspace.

npm install
Enter fullscreen mode Exit fullscreen mode

And finally you can import the storybook component from all modules

// web/modules/root/src/App.js
import './App.css'
import { Header, Button } from "@fstr/components"

function App() {
  return (
    <div className="App">
      <Header text="from root" />
      <Button
        label="Button"
        onClick={() => { }}
      />
    </div>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

Run the root module to see the changes

npm start -w @fstr/root
Enter fullscreen mode Exit fullscreen mode

Discussion (0)