HOW TO SETUP STORYBOOK WITH NEXTJS
Tags: typescript, nextjs, javascript, webdev
Published: 2023-06-12 08:15:20

**Introduction:**

Storybook is a vital tool for developing and documenting UI components.
It enables isolated component environments for efficient testing and sharing.
With its visual reference, Storybook promotes better collaboration and understanding within teams.
By showcasing components in different states, it ensures UI consistency and improves the developer experience.
Overall, Storybook streamlines development, enhances code quality, and encourages modular and reusable code.

**_The version of Storybook used in this tutorial is 7.0.11._**

1/ **Initialization**
Storybook simplifies the setup process with its handy initializer: npx sb init. This initializer automatically detects the project type and adjusts accordingly. However, we can provide additional hints if needed.

For projects using Next.js v11 and later, which utilize Webpack 5, we can enhance integration and performance by configuring Storybook to use Webpack 5 as well. To achieve this, we utilize the builder option and execute the following command:

```
npx sb init --builder webpack5
```
2/ **Add webpack resolution:** 

//package.json
```
 "resolutions": {
    "webpack": "^5"
  }
```

3/ **in your .storybook/main.js file may you need this changes:**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pgxr92ng0diwtvpfumwh.png)

4/ a custom preview.js and main.js files you can use

▶️ ./peview.js

```
import '../styles/main.scss';
import * as NextImage from 'next/image';

const OriginalNextImage = NextImage.default;

Object.defineProperty(NextImage, 'default', {
  configurable: true,
  value: (props) => <OriginalNextImage {...props} unoptimized />,
});

export const parameters = {
  actions: { argTypesRegex: '^on[A-Z].*' },
  controls: {
    matchers: {
      color: /(background|color)$/i,
      date: /Date$/,
    },
  },
  previewTabs: {
    'storybook/docs/panel': { index: -1 },
  },
};

```

▶️ ./main.js

```
// .storybook/main.js

const path = require('path');

module.exports = {
  //To specify the location from which Storybook should read stories..
  stories: [
    '../stories/**/*.mdx',
    '../stories/**/*.stories.@(js|jsx|ts|tsx)',
    '../components/**/*.mdx',
    '../components/**/*.stories.@(js|jsx|ts|tsx)',
  ],
  // Specify the  location of our styles
  staticDirs: ['../public'],
  framework: '@storybook/nextjs',
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-essentials',
    '@storybook/addon-interactions',
    '@storybook/addon-coverage',
    {
      /**
       * NOTE: fix Storybook issue with PostCSS@8
       * @see https://github.com/storybookjs/storybook/issues/12668#issuecomment-773958085
       */
      name: '@storybook/addon-postcss',
      options: {
        postcssLoaderOptions: {
          implementation: require('postcss'),
        },
      },
    },
  ],
  core: {
    builder: 'webpack5',
  },
  webpackFinal: (config) => {
    /**
     * Add support for alias-imports
     * @see https://github.com/storybookjs/storybook/issues/11989#issuecomment-715524391
     */
    config.resolve.alias = {
      ...config.resolve?.alias,
      '@': [path.resolve(__dirname, '../src/'), path.resolve(__dirname, '../')],
    };

    /**
     * Fixes font import with /
     * @see https://github.com/storybookjs/storybook/issues/12844#issuecomment-867544160
     */
    config.resolve.roots = [path.resolve(__dirname, '../public'), 'node_modules'];

    return config;
  },
};

```
⚠️ : if you will use this file you need to install all of the addons :

```
npm i  @storybook/addon-links
npm i  @storybook/addon-essentials
npm i  @storybook/addon-interactions
npm i  @storybook/addon-coverage,
```

We will discuss this section and its utilities in upcoming chapters:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cr1p4jigai5xnpqb6kj2.png)

5/ in your package.json you will have something like this: 
./scripts:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jrcedpisqfinpkhfk951.png)

6/ **To run Storybook, simply type**

```
yarn run storybook 
```
or

```
npm run storybook
```

you will get this :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3op2z5b3djci31lj7y0l.png)


In the upcoming chapters, we will cover the following topics:

1️⃣ Creating Components: We will learn how to create components in Storybook.

2️⃣ Testing Components with Storybook: We will explore how to leverage Storybook to test and showcase your components in isolation.

3️⃣ Creating Interactions and Scenarios: We will dive into creating interactive stories and scenarios within Storybook, enabling you to simulate user interactions and showcase different usage scenarios of your components.