StorybookEmotion 11エラーなる問題解決方法

3 min read
hiroweb developer

状況

Emotionを利用してコンポーネント開発をしてる。Storybookからコンポーネントを参照したところ Storybook のビルド時に下記のようなエラーが発生した。

ERROR in ./src/components/Button.tsx
Module not found: Error: Can't resolve '@emotion/styled/base' in 〜

次に、先述のエラーを解消したところ、import { css } from '@emotion/react'を利用している箇所の CSS が上手く反映されておらず、下記のメッセージが表示されていた。

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).

上記のエラーへの対応方法を記述する。

環境

  • @emotion/babel-plugin: 11.3.0
  • @emotion/react: 11.5.0
  • @emotion/styled: 11.3.0
  • @storybook/react: 6.3.12
  • next: 12.0.2

Next.jsStorybook が共存している状態。

解決方法

ビルドエラーの解決

.storybook/main.jsで webpack の alias を下記のように書き換えることでビルドが正常にできるようになる。

// .storybook/main.js
const path = require("path");
const toPath = (_path) => path.join(process.cwd(), _path);

module.exports = {
  // ...中略
  webpackFinal: async (config) => {
    return {
      ...config,
      resolve: {
        ...config.resolve,
        alias: {
          ...config.resolve.alias,
          "@emotion/core": toPath("node_modules/@emotion/react"),
          "@emotion/styled": toPath("node_modules/@emotion/styled"),
          "emotion-theming": toPath("node_modules/@emotion/react"),
        },
      },
    };
  },
};

Storybook のアドオンが内部依存している Emotion のバージョンが違うのことが問題のようであった。

ERROR in ./src/components/Button.tsx
Module not found: Error: Can't resolve '@emotion/styled/base' in 〜

CSS prop のエラー解決

Next.jsが参照しているルートの babel.config は Storybook に反映されていないようなので、Storybook 用の babel.config を用意して、@emotion/babel-pluginを指定し直した。

// .storybook/babel.config.js
module.exports = {
  plugins: ["@emotion/babel-plugin"],
};

これで CSS prop のエラーが解消した。

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).

参考