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:
- run
gatsby new
selecting defaults and styled-components as styling system - run
npm install --save @mui/material @mui/styled-engine-sc styled-components
from the mui install instructions for styled-components - 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. - try
gatsby develop
but it will fail withModuleNotFoundError: 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:
- material-ui-v5-not-working-styled-components-and-typescript
- using-material-ui-theming-with-styled-component
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.