1

I am trying to use Gatsby with MUI and Styled-Components. However I get the following error message: ModuleNotFoundError: Module not found: Error: Can't resolve '@emotion/react' that is unusual because the docs say that styled-components can be used exclusively as the styling solution.

Steps to reproduce:

  1. run gatsby new selecting defaults and styled-components as styling system
  2. run npm install --save @mui/material @mui/styled-engine-sc styled-components from the mui install instructions for styled-components
  3. add import Button from "@mui/material/Button"; to the imports and <Button variant="contained">Hello World</Button> in the main div of the index.js file. From the docs.
  4. try gatsby develop but it will fail with ModuleNotFoundError: Module not found: Error: Can't resolve '@emotion/react' this is the problem.

What I tried:

  • I tried npm i --save @emotion/react @emotion/styled and the button renders but i'm not sure if it renders with styled-components or emotion, probably emotion.
  • I tried to alias @mui/styled-engine to @mui/styled-engine-sc the wrapper around styled-components as described here in the mui docs and here in the Gatsby docs but I don't think that's related to my problem because if anything i would need to alias @emotion/styled to some other package.
  • I looked at Gatsby theme materialui but that mentions SSR and the docs says SSR doesn't work with styled-components and npm here. Do I have to use Yarn?

Related SO Questions:

Other related links:

  • this Github example uses gatsby-theme-material-ui but i think that uses SSR which is broken with npm and styled-components.

Best solution I found so far is to not use styled-components and rather use emotion and the styled() option from @mui/styled as described here.

defimeditations
  • 151
  • 1
  • 3
  • 11

1 Answers1

0

Instructions are indeed not clear, you have to add these dev dependecies and this resolution part in your package.json file:

{
  "dependencies": {
    "@mui/material": "^5.13.4",
    "styled-components": "^6.0.0-rc.3",
  },
  "devDependencies": {
    "@mui/styled-engine": "npm:@mui/styled-engine-sc@latest",
  },
  "resolutions": {
    "@mui/styled-engine": "npm:@mui/styled-engine-sc@latest"
  }
}

And also this one in devDependencies in you use Typescript: "@types/styled-components": "^5.1.26",

Simon
  • 6,025
  • 7
  • 46
  • 98