storybook: Storybook throw error if used emotion 11

Describe the bug Problem with emotion 11 : Module not found: Error: Can’t resolve ‘@emotion/styled/base’

To Reproduce yarn storybook

Code snippets

import styled from '@emotion/styled'
export const Text = styled.span`
  color: #000;
`

System

OS: macOS 11.0.1
CPU: (4) x64 Intel(R) Core(TM) i5-7267U CPU @ 3.10GHz
Node: 14.15.1 - /var/folders/0l/rm1hc02j23nb4nd9lzpwxf1m0000gp/T/fnm_multishell_78935_1606337172547/bin/node
Yarn: 1.22.4 - /usr/local/bin/yarn
npm: 6.14.8 - /var/folders/0l/rm1hc02j23nb4nd9lzpwxf1m0000gp/T/fnm_multishell_78935_1606337172547/bin/npm
Chrome: 87.0.4280.67
Firefox: 83.0
Safari: 14.0.1

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 85
  • Comments: 32 (6 by maintainers)

Commits related to this issue

Most upvoted comments

Why is this closed? this is still an issue affecting storybook and emotion 11

By adding "@emotion/core": toPath("node_modules/@emotion/react"), it starts to work:

const path = require("path")

const toPath = (_path) => path.join(process.cwd(), _path)

module.exports = {
  stories: [
    '../stories/start.stories.mdx',
    '../stories/**/*.stories.@([tj]sx|mdx)'
  ],
  addons: [
    '@storybook/addon-actions',
    '@storybook/addon-storysource',
    {
      name: '@storybook/addon-docs',
      options: {
        configureJSX: true,
      },
    }
  ],
  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"),
        }
      }
    };
  }
};

I also needed to change the definition of the actions addon. Please see: https://github.com/openscript/react-section-dividers/blob/0f22f4c483ed5f1abf226a73001bd91276797281/.storybook/main.js

Thank you @mverissimo and @mavlikwowa for looking into this. 🎄

It didn’t work for me. I’m using yarn workspaces, so node_modules is in some parent directory. I also have the bad tendency of moving files around, so I wanted a solution that keeps working.

This is what I came up with:

const fs = require('fs');
const path = require('path');

function getPackageDir(filepath) {
    let currDir = path.dirname(require.resolve(filepath));
    while (true) {
        if (fs.existsSync(path.join(currDir, 'package.json'))) {
            return currDir;
        }
        const { dir, root } = path.parse(currDir);
        if (dir === root) {
            throw new Error(`Could not find package.json in the parent directories starting from ${filepath}.`);
        }
        currDir = dir;
    }
}

Just replace toPath('node_modules/@emotion/react') with getPackageDir('@emotion/react') and you’re good to go.

In my opinion this issue should be reopened. I’m really stuck with this. I had to downgrade to emotion 10.

You need to use babel-preset-css-prop to development and @emotion/babel-plugin only for production.

I changed webpack.config in Storybook and it helped! `const path = require(“path”)

const toPath = (_path) => path.join(process.cwd(), _path)

module.exports = { stories: [‘…/stories/**/*.stories.@(ts|tsx|js|jsx)’], addons: [‘@storybook/addon-links’, ‘@storybook/addon-essentials’], // https://storybook.js.org/docs/react/configure/typescript#mainjs-configuration typescript: { check: true, // type-check stories during Storybook build }, webpackFinal: async (config) => { return { …config, resolve: { …config.resolve, alias: { …config.resolve.alias, “@emotion/core”: toPath(“node_modules/@emotion/react”), // You should add this row “@emotion/styled”: toPath(“node_modules/@emotion/styled”), “emotion-theming”: toPath(“node_modules/@emotion/react”), }, }, } }, }; `

Even with @emotion removed from plugins and I add “@emotion/babel-preset-css-prop” to presets I still getting

Module not found: Error: Can't resolve '@emotion/styled/base'

Their documents suggests it pulls in the plugin anyways.

@emotion/babel-preset-css-prop includes the emotion plugin. The @emotion/babel-plugin entry should be removed from your config and any options moved to the preset.

What I did:

  1. Deleted yarn.lock and node_modules
  2. Ran yarn install
  3. Ran yarn start:storybook

I’ve pushed the changes to the repo and branch mentioned above.

image

@openscript after updating my webpackFinal in the main.js to what you have above, I am still getting the “cannot redefine property: ClassNames” error:

Uncaught TypeError: Cannot redefine property: ClassNames
    at Function.defineProperty (<anonymous>)
    at vendors~main.562b20c117093708abb6.bundle.js:82465
    at Array.forEach (<anonymous>)
    at Object../node_modules/@storybook/core/node_modules/@storybook/theming/dist/index.js (vendors~main.562b20c117093708abb6.bundle.js:82462)
    at __webpack_require__ (runtime~main.562b20c117093708abb6.bundle.js:849)
    at fn (runtime~main.562b20c117093708abb6.bundle.js:151)
    at Object../node_modules/@storybook/core/node_modules/@storybook/components/dist/Badge/Badge.js (vendors~main.562b20c117093708abb6.bundle.js:68122)
    at __webpack_require__ (runtime~main.562b20c117093708abb6.bundle.js:849)
    at fn (runtime~main.562b20c117093708abb6.bundle.js:151)
    at Object../node_modules/@storybook/core/node_modules/@storybook/components/dist/index.js (vendors~main.562b20c117093708abb6.bundle.js:76001)

Here is my main.js:

const path = require('path');

const toPath = (_path) => path.join(process.cwd(), _path);

module.exports = {
  stories: ['../**/*.stories.js'],
  addons: ['@storybook/addon-essentials'],
  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'),
        },
      },
    };
  },
};

If you want this fixed, please upvote by adding a 👍 to the issue description. We use this to help prioritize!

@HosseinAgha i didn’t close this issue. if you want to track the open issue for emotion 11, it is https://github.com/storybookjs/storybook/issues/13145. we are actively working on a proper fix, though it’s non-trivial because we are also under the constraints of semver and are not ready to do a major release.

@HosseinAgha I didn’t close the issue. I just referenced it from the Nx repo where we implemented a fix for this.

Hey @shilman, the workarounds provided here are all hacky and not a fix.
The Webpack alias solution does not work for a yarn (v2) pnp environment.
@juristr could you please reopen the issue? I don’t think any of the provided solutions resolve the core issue.
I still think this is a serious issue with either storybook or emotion 11.

I had the problem (emotion 11) but i have only replaced @emotion/core by @emotion/react in my devDependencies and it’s ok now ! I hope it will help others!

@samvv MY HERO! 🔥

@openscript thanks for the fix! I can confirm that the fix works for me. 👍

Note: my project uses Gatsby, TypeScript, Emotion (I use styled and the css prop), and Storybook. I found this post particularly helpful in resolving issues I was running into using the emotion css prop. https://duncanleung.com/emotion-css-prop-jsx-pragma-storybook/

Here are the steps I ran through to resolve.

  1. Updated ./storybook/webpack.config.js
  2. Deleted yarn.lock and node_modules/.cache
  3. yarn storybook

Here is my main.js

const webpackFinal = require("./webpack.config")
module.exports = {
  stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
  addons: ["@storybook/addon-links", "@storybook/addon-essentials"],
  webpackFinal: async config => webpackFinal({ config }),
}

And here is my webpack.config.js

const path = require("path")
const toPath = _path => path.join(process.cwd(), _path)
module.exports = ({ config }) => {
  config.module.rules[0].exclude = [/node_modules\/(?!(gatsby)\/)/]
  // use @babel/preset-react for JSX and env (instead of staged presets)
  config.module.rules[0].use[0].options.presets = [
    require.resolve("@babel/preset-react"),
    require.resolve("@babel/preset-env"),
    require.resolve("@emotion/babel-preset-css-prop"),
  ]
  // ... other configs

  // Add Webpack rules for TypeScript
  // ========================================================
  config.module.rules.push({
    test: /\.(ts|tsx)$/,
    loader: require.resolve("babel-loader"),
    options: {
      presets: [
        ["react-app", { flow: false, typescript: true }],
        require.resolve("@emotion/babel-preset-css-prop"),
      ],
      // ... other configs
    },
  })
  // ... other configs

  config.resolve.extensions.push(".ts", ".tsx")

  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"),
  }

  return config
}

After I removed "emotion-theming": toPath("node_modules/@emotion/react"), it seems to work better, but other runtime errors occur.

Uncaught TypeError: theme.background is undefined
    node_modules vendors~main.f596980d4940e83ece7a.bundle.js:25756
    handleInterpolation emotion-serialize.browser.esm.js:137
    serializeStyles emotion-serialize.browser.esm.js:251
    Styled emotion-styled-base.browser.esm.js:110
    withEmotionCache emotion-element-4fbd89c5.browser.esm.js:27
    React 17
    renderDocs StoryRenderer.js:502
    _callee2$ StoryRenderer.js:294
    Babel 8
    _callee$ StoryRenderer.js:194
    Babel 8
    setupListeners StoryRenderer.js:121
    handleEvent index.js:196
    handleEvent index.js:195
    handler index.js:121
    emit index.js:128
    setSelection story_store.js:920
    finishConfiguring story_store.js:471
    configure config_api.js:33
    loadCsf loadCsf.js:333
    configure index.js:35
    js generated-stories-entry.js:6
    js main.f596980d4940e83ece7a.bundle.js:18
    Webpack 7
DocsPage.js:70
    DocsWrapper DocsPage.js:70
    handleInterpolation emotion-serialize.browser.esm.js:137
    serializeStyles emotion-serialize.browser.esm.js:251
    Styled emotion-styled-base.browser.esm.js:110
    withEmotionCache emotion-element-4fbd89c5.browser.esm.js:27
    React 17
    renderDocs StoryRenderer.js:502
    _callee2$ StoryRenderer.js:294
    Babel 8
    _callee$ StoryRenderer.js:194
    Babel 8
    setupListeners StoryRenderer.js:121
    handleEvent index.js:196
    forEach self-hosted:206
    handleEvent index.js:195
    handler index.js:121
    emit index.js:128
    setSelection story_store.js:920
    finishConfiguring story_store.js:471
    configure config_api.js:33
    loadCsf loadCsf.js:333
    configure index.js:35
    js generated-stories-entry.js:6
    js main.f596980d4940e83ece7a.bundle.js:18