New
Storybook’s Visual Tests addon enters betaVisual test with Chromatic
Star82,133
New
You're viewing older docs for version 7.0. View latest docs

Write an addon

Storybook addons are a powerful way to extend Storybook's functionality and customize the development experience. They can be used to add new features, customize the UI, or integrate with third-party tools.

What are we going to build?

This reference guide is to help you develop a mental model for how Storybook addons work by building a simple addon based on the popular Outline addon. Throughout this guide, you'll learn how addons are structured, Storybook's APIs, how to test your addon locally, and how to publish it.

Addon anatomy

There are two main categories of addons, each with its role:

  • UI-based: These addons are responsible for customizing the interface, enabling shortcuts for common tasks, or displaying additional information in the UI.
  • Presets: These are pre-configured settings or configurations that enable developers to quickly set up and customize their environment with a specific set of features, functionality, or technology.

UI-based addons

The addon built in this guide is a UI-based addon, specifically a toolbar addon, enabling users to draw outlines around each element in the story through a shortcut or click of a button. UI addons can create other types of UI elements, each with its function: panels and tabs, providing users with various ways to interact with the UI.

Setup

To create your first addon, you're going to use the Addon Kit, a ready-to-use template featuring all the required building blocks, dependencies and configurations to help you get started building your addon. In the Addon Kit repository, click the Use this template button to create a new repository based on the Addon Kit's code.

Clone the repository you just created and install its dependencies. When the installation process finishes, you will be prompted with questions to configure your addon. Answer them, and when you're ready to start building your addon, run the following command to start Storybook in development mode and develop your addon in watch mode:

ℹ️ The Addon Kit uses Typescript by default. If you want to use JavaScript instead, you can run the eject-ts command to convert the project to JavaScript.

Understanding the build system

Addons built in the Storybook ecosystem rely on tsup, a fast, zero-config bundler powered by esbuild to transpile your addon's code into modern JavaScript that can run in the browser. Out of the box, the Addon Kit comes with a pre-configured tsup configuration file that you can use to customize the build process of your addon.

When the build scripts run, it will look for the configuration file and pre-bundle the addon's code based on the configuration provided. However, there are a few properties that are worth referencing:

  • entry: Configures the files to be processed by the bundler. It can be extended to include additional files using a regex pattern.
  • format: Enables the generation of multiple output formats. In this case, we're generating a CommonJS and an ES Module version of our addon.
  • dts: Auto-generates type definitions for our addon.
  • platform: Specifies the target platform for our addon. In this case, we're targeting the browser. It can be set to node for Node.js environments or neutral for universal modules.

Register the addon

By default, code for the UI-based addons is located in one of the following files, depending on the type of addon built: src/Tool.tsx, src/Panel.tsx, or src/Tab.tsx. Since we're building a toolbar addon, we can safely remove the Panel and Tab files and update the remaining file to the following:

Going through the code blocks in sequence:

Loading...

The useGlobals and useStorybookApi hooks from the manager-api package are used to access the Storybook's APIs, allowing users to interact with the addon, such as enabling or disabling it. The Icons and IconButtons components from the @storybook/components package render the icons and buttons in the toolbar.

Loading...

The Tool component is the entry point of the addon. It renders the UI elements in the toolbar, registers a keyboard shortcut, and handles the logic to enable and disable the addon.

Moving onto the manager, here we register the addon with Storybook using a unique name and identifier. Since we've removed the Panel and Tab files, we'll need to adjust the file to only reference the addon we're building.

Notice the match property. It allows you to control the view mode where the addon is visible. If you only want to show it in a single mode, you must adjust the property to match the specific mode you aim for. In this case, it will be available in both story and documentation.

Run the start script to build and start Storybook and verify that the addon is registered correctly and showing in the UI.

Addon registered in the toolbar

Style the addon

In Storybook, applying styles for addons is considered a side-effect. Therefore, we'll need to make some changes to our addon to allow it to use the styles when it is active and remove them when it's disabled. We're going to rely on two of Storybook's features to handle this: decorators and globals. To handle the CSS logic, we must include some helper functions to inject and remove the stylesheets from the DOM. Start by creating the helper file with the following content:

Next, create the file with the styles we want to inject with the following content:

Since the addon can be active in both the story and documentation modes, the DOM node for Storybook's preview iframe is different in these two modes. In fact, Storybook renders multiple story previews on one page when in documentation mode. Therefore, we'll need to choose the correct selector for the DOM node where the styles will be injected and ensure the CSS is scoped to that particular selector. That mechanism is provided as an example within the src/withGlobals.ts file, which we'll use to connect the styling and helper functions to the addon logic. Update the file to the following:

Packaging and publishing

Storybook addons, similar to most packages in the JavaScript ecosystem, are distributed as NPM packages. However, they have specific criteria that need to be met to be published to NPM and crawled by the integration catalog:

  1. Have a dist folder with the transpiled code.
  2. A package.json file declaring:
    • Peer dependencies
    • Module-related information
    • Integration catalog metadata

Module Metadata

The first category of metadata is related to the addon itself. This includes the entry for the module and which files to include when the addon is published. And all the peer-dependencies of the addon (e.g., react,react-dom, and Storybook's related APIs).

Loading...

Why peer-dependencies?

A standard practice in the JavaScript ecosystem ensuring compatibility between modules or packages that are meant to work together, often in a plugin or extension scenario. Peer-dependencies are dependencies that are not bundled with the addon but are expected to be installed by the consumer of the addon. When a module relies on a specific version of another module, it might assume certain features, APIs, or behavior provided by that dependency. By specifying a peer dependency, the module can indicate its compatibility requirements and avoid potential conflicts or unexpected behavior due to incompatible versions.

Integration Catalog Metadata

The second metadata category is related to the integration catalog. Most of this information is already pre-configured by the Addon Kit. However, items like the display name, icon, and frameworks must be configured via the storybook property to be displayed in the catalog.

Loading...

ℹ️ The storybook configuration element includes additional properties that help customize the addon's searchability and indexing. For more information, see the Integration catalog documentation.

One essential item to note is the keywords property as it maps to the catalog's tag system. Adding the storybook-addons ensures that the addon is discoverable in the catalog when searching for addons. The remaining keywords help with the searchability and categorization of the addon.

Publishing to NPM

Once you're ready to publish your addon to NPM, the Addon Kit comes pre-configured with the Auto package for release management. It generates a changelog and uploads the package to NPM and GitHub automatically. Therefore, you need to configure access to both.

  1. Authenticate using npm adduser
  2. Generate a access token with both read and publish permissions.
  3. Create a personal access token with repo and workflow scoped permissions.
  4. Create a .env file in the root of your project and add the following:
Loading...

Next, run the following command to create labels on GitHub. You'll use these labels to categorize changes to the package.

Terminal
Loading...

Finally, run the following command to create a release for your addon. This will build and package the addon code, bump the version, push the release into GitHub and npm, and generate a changelog.

CI automation

By default, the Addon Kit comes pre-configured with a GitHub Actions workflow, enabling you to automate the release management process. This ensures that the package is always up to date with the latest changes and that the changelog is updated accordingly. However, you'll need additional configuration to use your NPM and GitHub tokens to publish the package successfully. In your repository, click the Settings tab, then the Secrets and variables dropdown, followed by the Actions item. You should see the following screen:

GitHub secrets page

Then, click the New repository secret, name it NPM_TOKEN, and paste the token you generated earlier. Whenever you merge a pull request to the default branch, the workflow will run and publish a new release, automatically incrementing the version number and updating the changelog.

Learn more about the Storybook addon ecosystem

Was this page helpful?

Markdown accepted ([link text](url), _italic_, **bold**, etc). Your anonymous feedback will be posted publicly on GitHub.

✍️ Edit on GitHub – PRs welcome!
Storybook
Join the community
6,517 developers and counting
WhyWhy StorybookComponent-driven UI
Open source software
Storybook

Maintained by
Chromatic
Special thanks to Netlify and CircleCI