Open2

vite + emotion + storybook で emotion が適応されなくて困ったさん

hanetsukihanetsuki

storybook に builder-vite を適応して Emotionでスタイリングする際に下記のような文言が className に表示された。

You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop).

色々調べていたら下記のissueに巡り合った。

https://github.com/storybookjs/builder-vite/issues/210

.storybook/main.js
const react = require("@vitejs/plugin-react");

module.exports = {
  stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
  addons: ["@storybook/addon-links", "@storybook/addon-essentials"],
  framework: "@storybook/react",
  core: {
    builder: "storybook-builder-vite",
  },
  async viteFinal(config) {
    config.plugins = config.plugins.filter(
      (plugin) =>
        !(Array.isArray(plugin) && plugin[0]?.name.includes("vite:react"))
    );

    config.plugins.push(
      react({
        exclude: [/\.stories\.(t|j)sx?$/, /node_modules/],
        jsxImportSource: "@emotion/react",
        babel: {
          plugins: ["@emotion/babel-plugin"],
        },
      })
    );

    console.log(config.plugins);
    return config;
  },
};

上記の設定を記述したら動きました。めでたしめでたし

hanetsukihanetsuki

Globalスタイルを当てたいときはpreview.jsxに記述する

.storybook/preview.jsx
import { Global } from '@emotion/react';
import { globalStyles } from '../src/styles/global.styles';

export const parameters = {
  actions: { argTypesRegex: "^on[A-Z].*" },
  controls: {
    matchers: {
      color: /(background|color)$/i,
      date: /Date$/,
    },
  },
}

export const decorators = [
  (Story) => {
    return (
      <>
        <Global styles={globalStyles} />
        <Story />
      </>
    )
  },
]