Closed4

storybook v7 で tailwind を使えるようにする

nbstshnbstsh

この記事に沿ってやっていく

https://storybook.js.org/recipes/tailwindcss

nbstshnbstsh

Auto-config

As of version 1.1, @storybook/addon-styling offers a codemod for to automatically configure your storybook with Tailwind.

必要な設定を自動で追加してくれる処理が用意されてるので以下コマンドを実行するだけでOK

node node_modules/@storybook/addon-styling/bin/postinstall.js

実行するとこうなる↓

=========================================

 🧰 Configuring @storybook/addon-styling

=========================================

(1/3) Project summary
  • Built with webpack
  • Styled with tailwind

(2/3) .storybook/main.ts
  • Registering @storybook/addon-styling.
    • Configuring postcss.

(3/3) .storybook/preview.tsx
  • Adding import for withThemeByClassName decorator
  • Adding import for stylesheet
  • Adding withThemeByClassName decorator to config

✨ Done
nbstshnbstsh

変更内容

storybook の main.ts と preview.tsx に以下の変更が加わる。

main.ts 更新

main.ts

const config: StorybookConfig = {
  framework: '@storybook/react-webpack5',
  stories: ['../src/**/stories.@(js|jsx|ts|tsx)'],
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-essentials',
    '@storybook/addon-interactions',
+    {
+      name: '@storybook/addon-styling',
+      options: {
+        postCss: {
+          implementation: require.resolve('postcss'),
+        },
+     },
+   },
  ],
  docs: {
    autodocs: 'tag',
  }
};

export default config;

preview.tsx

preview.tsx
import { Preview } from '@storybook/react';
import React from 'react';

+import { withThemeByClassName } from '@storybook/addon-styling';
+
+/* TODO: update import to your tailwind styles file. If you're using Angular, inject this through your angular.json config instead */
+import '../src/index.css';


const preview: Preview = {
  decorators: [
    // Adds theme switching support.
    // NOTE: requires setting "darkMode" to "class" in your tailwind config
+   withThemeByClassName({
+     themes: {
+       light: 'light',
+       dark: 'dark',
+     },
+     defaultTheme: 'light',
+   }),
  ],
  parameters: {
    actions: { argTypesRegex: '^on[A-Z].*' },
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/,
      },
    },
    layout: 'fullscreen',
  },
};

export default preview;
このスクラップは2023/07/15にクローズされました