Search code examples
reactjsmaterial-uistorybook

Cannot use material-ui with storybook "Can't resolve '@emotion/react'"


I am using webpack@5 for storybook of my project. The problem is when I use my component in storybook (which uses material-ui components) I get error:

ModuleNotFoundError: Module not found: Error: Can't resolve '@emotion/react' in '/Users/USER/Dev/PROJECT/front/packages/components/node_modules/@mui/styled-engine/GlobalStyles'

I have tried to install this package, add it to addons, add alias for this module to storybook config, install other strange material-ui modules. Nothing works for me, still the same error.

Can you help and suggest what I can try to solve this?


Solution

  • So I found some solution on a page and it works for me:

    //main.js
    webpackFinal: async (config) => {
        return merge(config, {
          resolve: {
            alias: {
              '@emotion/react': getPackageDir('@emotion/react'),
            },
          },
        });
      },
    
    //main.js
    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;
      }
    }