Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Storybook throw error if used emotion 11 #13277

Closed
pgrekovich opened this issue Nov 25, 2020 · 32 comments
Closed

Storybook throw error if used emotion 11 #13277

pgrekovich opened this issue Nov 25, 2020 · 32 comments

Comments

@pgrekovich
Copy link

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
@mverissimo
Copy link

mverissimo commented Nov 25, 2020

Hi, do you have a repro case?

Related issues: #13145 #12114

@pgrekovich
Copy link
Author

The problem seems to be in the @emotion/babel-plugin. When I turned it off, the problem had fixed.

I made a repository where the problem is reproduced: storybook-emotion-bug

@mverissimo
Copy link

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

@pgrekovich
Copy link
Author

You are right, thanks!
babel-preset-css-prop insted of @emotion/babel-plugin fixed the problem

@Kalcode
Copy link

Kalcode commented Dec 8, 2020

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.

@pradyuman
Copy link

Same here.

1 similar comment
@cmwhited
Copy link

Same here.

tupcuturan35 referenced this issue Dec 18, 2020
There is a number() typo instead of text()
@shilman
Copy link
Member

shilman commented Dec 19, 2020

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

@openscript
Copy link

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

@mverissimo
Copy link

So, share a repro case with us, and maybe we can help you.

@mavlikwowa
Copy link

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

@openscript
Copy link

So, share a repro case with us, and maybe we can help you.

With this repository the error can be reproduced: https://github.com/openscript/react-section-dividers/tree/feat/emotion11

  1. Checkout the branch feat/emotion11
  2. Run yarn install
  3. Run yarn start:storybook
ERROR in ./src/Polygon.tsx
Module not found: Error: Can't resolve '@emotion/styled/base' in '/workspaces/react-section-dividers/src'
 @ ./src/Polygon.tsx 2:0-43 5:14-21
 @ ./stories/Polygon.stories.tsx
 @ ./stories sync ^\.(?:(?:^|\/|(?:(?:(?!(?:^|\/)\.).)*?)\/)(?!\.)(?=.)[^/]*?\.stories\.((?:\[tj\]|[tj])sx|mdx))$
 @ ./.storybook/generated-stories-entry.js
 @ multi ./node_modules/@storybook/core/dist/server/common/polyfills.js ./node_modules/@storybook/core/dist/server/preview/globals.js ./.storybook/storybook-init-framework-entry.js ./node_modules/@storybook/addon-docs/dist/frameworks/common/config.js-generated-other-entry.js ./node_modules/@storybook/addon-docs/dist/frameworks/react/config.js-generated-other-entry.js ./.storybook/preview.js-generated-config-entry.js ./.storybook/generated-stories-entry.js (webpack)-hot-middleware/client.js?reload=true&quiet=false&noInfo=undefined

Environment:

Environment Info:

  System:
    OS: Linux 5.9 Debian GNU/Linux 10 (buster) 10 (buster)
    CPU: (8) x64 Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
  Binaries:
    Node: 14.14.0 - /usr/local/bin/node
    Yarn: 1.22.5 - /usr/bin/yarn
    npm: 6.14.8 - /usr/local/bin/npm
  npmPackages:
    @storybook/addon-essentials: ^6.1.11 => 6.1.11 
    @storybook/addon-info: ^5.3.21 => 5.3.21 
    @storybook/addon-links: ^6.1.11 => 6.1.11 
    @storybook/addon-storysource: ^6.1.11 => 6.1.11 
    @storybook/addons: ^6.1.11 => 6.1.11 
    @storybook/react: ^6.1.11 => 6.1.1

@mverissimo
Copy link

mverissimo commented Dec 28, 2020

Hi, did you try the solution above? This looks like works!

@openscript
Copy link

openscript commented Dec 28, 2020

Right, did you try the solution above? This looks like works!

I've changed my main.js to this:

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/register',
    '@storybook/addon-storysource',
    {
      name: '@storybook/addon-docs',
      options: {
        configureJSX: true,
      },
    }
  ],
  webpackFinal: async (config) => {
    return {
      ...config,
      resolve: {
        ...config.resolve,
        alias: {
          ...config.resolve.alias,
          "@emotion/styled": toPath("node_modules/@emotion/styled"),
          "emotion-theming": toPath("node_modules/@emotion/react"),
        }
      }
    };
  }
};

It's builds, but I've a runtime error:

Uncaught TypeError: can't redefine non-configurable property "ClassNames"
    node_modules vendors~main.d581e313e4b0af6901e7.bundle.js:34278
    node_modules vendors~main.d581e313e4b0af6901e7.bundle.js:34274
    Webpack 22
        __webpack_require__
        fn
        node_modules
        __webpack_require__
        fn
        node_modules
        __webpack_require__
        fn
        node_modules
        __webpack_require__
        fn
        node_modules
        __webpack_require__
        fn
        node_modules
        __webpack_require__
        fn
        0

I don't know. Cannot figure out this. With Emotion 10 everything works flawlessly

@mverissimo
Copy link

Stranger, I do the same thing e here works fine, try to generate a new yarn.lock and please commit these changes to be possible to make tests here.

openscript added a commit to openscript/react-section-dividers that referenced this issue Dec 28, 2020
@openscript
Copy link

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
Copy link

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

@openscript
Copy link

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

@cmwhited
Copy link

cmwhited commented Dec 28, 2020

@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'),
        },
      },
    };
  },
};

@openscript
Copy link

openscript commented Dec 28, 2020

@cmwhited Have you deleted the cache (node_modules/.cache)? Maybe also the yarn.lock file (I did that too, but don't know if this changed anything)?

@cmwhited
Copy link

Yeah I deleted the node_modules and the yarn.lock

@openscript
Copy link

openscript commented Dec 28, 2020

Very strange, indeed. Can you try mine? https://github.com/openscript/react-section-dividers/tree/feat/emotion11

  1. Clone & checkout feat/emotion11
  2. yarn install
  3. yarn start:storybook

@tylerben
Copy link

@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
}

@Vadorequest
Copy link

I can confirm changing the webpack mapping works as explained in #13277 (comment)

See commit
See full PR UnlyEd/next-right-now#251

@samvv
Copy link
Contributor

samvv commented Jan 22, 2021

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.

@ArtyomResh
Copy link
Contributor

ArtyomResh commented Jan 27, 2021

@samvv MY HERO! 🔥

@davidcsally
Copy link
Contributor

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

@neokeld
Copy link

neokeld commented Feb 18, 2021

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!

pvenable added a commit to CatchRelease/arbor that referenced this issue Mar 26, 2021
Some additional aliasing in `.storybook/main.js` resolved the rendering
errors we saw previously.

For more context, see:
storybookjs/storybook#13277 (comment)

[#177401579]
pvenable added a commit to CatchRelease/arbor that referenced this issue Mar 26, 2021
Some additional aliasing in `.storybook/main.js` resolved the rendering
errors we saw previously.

For more context, see:
storybookjs/storybook#13277 (comment)

[#177401579]
@elie222
Copy link

elie222 commented Mar 31, 2021

Adding this file got it to work for us with JS (although not with TS):
https://github.com/ben-rogerson/twin.examples/blob/6f7cec73ae/storybook-emotion/.storybook/.babelrc

.storybook/.babelrc:

{
  "plugins": [
    "babel-plugin-macros",
    [
      "@emotion/babel-plugin-jsx-pragmatic",
      {
        "export": "jsx",
        "import": "__cssprop",
        "module": "@emotion/react"
      }
    ],
    [
      "@babel/plugin-transform-react-jsx",
      {
        "pragma": "__cssprop"
      }
    ]
  ]
}

@HosseinAgha
Copy link

HosseinAgha commented Oct 25, 2021

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.

@juristr
Copy link
Contributor

juristr commented Oct 25, 2021

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

@shilman
Copy link
Member

shilman commented Oct 25, 2021

@HosseinAgha i didn't close this issue. if you want to track the open issue for emotion 11, it is #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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests