material-ui icon indicating copy to clipboard operation
material-ui copied to clipboard

[styled-engine-sc] MUI + styled-components + Next.js CSS rules ordering issue

Open zibra opened this issue 3 years ago โ€ข 61 comments

Duplicates

  • [X] I have searched the existing issues

Latest version

  • [X] I have tested the latest version

Current behavior ๐Ÿ˜ฏ

Next.js projects using MUI + styled-components based on the example configuration from:\ have incorrect MUI components styling on production. The order of the CSS rules is different from SSR and after hydration.

Expected behavior ๐Ÿค”

UI elements looks always same (on dev run and on production). CSS rules are applied always in the same order.

Steps to reproduce ๐Ÿ•น

Steps:

  1. visit https://codesandbox.io/s/heuristic-framework-2leki?file=/pages/about.tsx
  2. refresh preview after server build and run the prod bundle
  3. navigate between pages + play with refreshing pages (to load SSR styles)

Video preview: https://www.youtube.com/watch?v=A0dqNA8IO4Q

Context ๐Ÿ”ฆ

When I was testing it locally it happened only on production builds, but in code sandbox it happens also on development mode. Just css class order is different between dev and prod.

Privided code sanbox is a fork for from official example from: https://github.com/mui-org/material-ui/tree/master/examples/nextjs-with-styled-components-typescript

I've just added 2 more buttons.

There are different states for the buttons depending on the scenario: Correct styling: obraz

Incorrect styling: obraz

CSS rules order comparison: obraz

Your environment ๐ŸŒŽ

I've tested this issue on Windows 10, Mac OS, AWS Amplify and at the end I've found that it also happens on CodeSandbox example. Always with latest versions with MUI, Next, node and styled-components

zibra avatar Nov 17 '21 21:11 zibra

Today I've tried same code with example using emotion (no styled-components and I was not able to reproduce such issues there. Code sandbox: https://codesandbox.io/s/gracious-blackburn-u4rw1?file=/pages/about.tsx

Maybe it's styled-components issue or configuration for SC

zibra avatar Nov 18 '21 12:11 zibra

I've tried wrapping components tree with StyledEngineProvider with injectFirst in _app.tsx but it's making no difference

zibra avatar Nov 18 '21 14:11 zibra

@mnajdova could you please take a look at this one?

zibra avatar Nov 18 '21 15:11 zibra

Maybe it's styled-components issue or configuration for SC

+1 this, found I didn't remove emotion completely and added in the required to my package.json (I'm using yarn if it makes any difference here)

"@mui/styled-engine": "npm:@mui/styled-engine-sc@latest",
"resolutions": {
  "@mui/styled-engine": "npm:@mui/styled-engine-sc@latest"
}

Now upon a deployment I've found my emotion is correctly removed but I have now styling inconsistencies.

Edit: Upon further investigation i'm getting the following.

It looks like there are several instances of 'styled-components' initialized in this application. This may cause dynamic styles to not render properly, errors during the rehydration process, a missing theme prop, and makes your application bigger without good reason.

https://styled-components.com/docs/faqs#why-am-i-getting-a-warning-about-several-instances-of-module-on-the-page

Haven't checked if this is occurring in a fresh NextJs, Material ui, styled-components but is probably my next step.

Edit again: I'm unsure on how to resolve my webpack issues as based on my reading the advice in the above link webpack.optimize.CommonsChunkPlugin was deprecated v4 and nextjs is default v5..

Further investigation found https://github.com/mui-org/material-ui/issues/24109 which the moral of the story is inconsistencies with styling in injection order due to emotion / styled-components and seems to have been removed from the milestone v5.1

cjmcintyre avatar Nov 19 '21 06:11 cjmcintyre

For now the only solution that I've found, was to switch my whole project to emotion...

zibra avatar Nov 19 '21 21:11 zibra

For now the only solution that I've found, was to switch my whole project to emotion...

@zibra not my favourite resolution but also the direction I'll probably take.

cjmcintyre avatar Nov 19 '21 21:11 cjmcintyre

This is the same issue as #29210 , the problem is the compatibility with the Link component. Using an <a> tag instead fixes the problem. Though you will obviously lose the benefits of the Link component.

AndyW22 avatar Nov 22 '21 18:11 AndyW22

This is the same issue as #29210 , the problem is the compatibility with the Link component. Using an <a> tag instead fixes the problem. Though you will obviously lose the benefits of the Link component.

@AndyW22 Is it the same problem?

I noticed in your example you don't use the provided example from material so therefore you are lacking the custom Link component. that they provide. In the sandbox url above the Link component provided by the example is the one being utilised.

cjmcintyre avatar Nov 23 '21 03:11 cjmcintyre

This is the same issue as #29210 , the problem is the compatibility with the Link component. Using an <a> tag instead fixes the problem. Though you will obviously lose the benefits of the Link component.

@AndyW22 Is it the same problem?

I noticed in your example you don't use the provided example from material so therefore you are lacking the custom Link component. that they provide. In the sandbox url above the Link component provided by the example is the one being utilised.

unfortunately their example repo doesnt actually use styled components at all, it simply sets it up in the project but doesnt use the styled function to actually make a styled component. I tried adding the CardContainer onto their example repo in the /about page and causes the same issue, so based on that their custom Link component doesn't fix this.

I also added it to the sandbox example and the same issue occurs at the same time as the other styling bugs, and, like with my example, using an <a> tag fixes the problem. I think it's most likely the same issue given on how they happen at the same time, styles have similar issues, they both seem to be caused by the Link component, and both fixed by the <a> tag.

AndyW22 avatar Nov 23 '21 11:11 AndyW22

I will look more into this tomorrow and post my findings

mnajdova avatar Nov 23 '21 12:11 mnajdova

I spent some time on this today, but haven't resolved it. At the start I thought the issue is that the babel-plugin-styled-components is not picking up the styled() coming from mui.

On this matter, I found the topLevelImportPaths option thanks to https://xstyled.dev/docs/migrate-from-styled-components/#babel-plugin (thank you @gregberge :))

I've tried updating the .babelrc to:

.babelrc

{
  "presets": ["next/babel"],
  "plugins": [
    [
      "babel-plugin-styled-components",
      {
        "topLevelImportPaths": [
          "@mui/material",
          "@mui/material/*",
          "@mui/system",
          "@mui/styled-engine-sc"
        ]
      }
    ]
  ]
}

There were some issues thrown at the start, that indicated that withConfig does not exists, so I believe the plugin started to pick up the imports from the styled() utility. I created https://github.com/mui-org/material-ui/pull/29873 and tried to use the packages build from it:

package.json

{
  "name": "nextjs-with-styled-components-typescript",
  "version": "5.0.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@mui/material": "https://pkg.csb.dev/mui-org/material-ui/commit/97b8bd28/@mui/material",
    "@mui/styled-engine-sc": "https://pkg.csb.dev/mui-org/material-ui/commit/97b8bd28/@mui/styled-engine-sc",
    "next": "latest",
    "next-transpile-modules": "latest",
    "react": "latest",
    "react-dom": "latest",
    "react-is": "latest",
    "styled-components": "latest"
  },
  "devDependencies": {
    "@types/react": "latest",
    "@types/styled-components": "latest",
    "babel-plugin-styled-components": "latest",
    "typescript": "latest"
  }
}

This did not work too. I even tried transpaling the mui packages using:

next.config.js

const path = require('path');
const withTM = require('next-transpile-modules')(['@mui/material', '@mui/system']) // pass the modules you would like to see transpiled

/** @type {import('next').NextConfig} */
module.exports = withTM({
  reactStrictMode: true,
  webpack: (config) => {
    config.resolve.alias = {
      ...config.resolve.alias,
      '@mui/styled-engine': '@mui/styled-engine-sc',
    };
    config.module = {
      ...config.module,
      rules: [
        {
          test: /\.js|jsx|ts|tsx$/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['next/babel'],
              plugins:  [
                [
                  "babel-plugin-styled-components",
                  {
                    "topLevelImportPaths": [
                      "@mui/material",
                      "@mui/material/styles",
                      "@mui/system",
                      "@mui/styled-engine-sc",
                      "@mui/styled-engine"
                    ],
                    "ssr": true
                  }
                ]
              ],
              include: [
                  path.resolve('*'),
                  path.resolve('node_modules/@mui/'),
              ],
              exclude: /node_modules\/(?!@mui).+/
            }
          }
        }
      ]
    }
    return config;
  },
})

But with no luck. the issue was still there. If someone wants to push further the investigation, make sure to use the packages from https://github.com/mui-org/material-ui/pull/29873, for example:

https://pkg.csb.dev/mui-org/material-ui/commit/97b8bd28/@mui/material
https://pkg.csb.dev/mui-org/material-ui/commit/97b8bd28/@mui/styled-engine-sc

I've pushed what I've tried in https://github.com/mui-org/material-ui/pull/29873

mnajdova avatar Nov 24 '21 15:11 mnajdova

cc @mui-org/core maybe someone will have a better idea than me

mnajdova avatar Nov 24 '21 15:11 mnajdova

Similar issues found on the styled-components repo:

  • https://github.com/styled-components/babel-plugin-styled-components/issues/358 - similar to our use-case
  • https://github.com/styled-components/babel-plugin-styled-components/issues/179 - another issue that may be relevant

mnajdova avatar Nov 25 '21 13:11 mnajdova

I have the same problem on my project

pedroeckel avatar Nov 25 '21 13:11 pedroeckel

One more update on the test project in #29873

I've copied our Typography component from mui locally there (I literally just changed the imports) and even added the custom styled.js utility we have in mui. The local copy of the Typography works, but the one imported from mui doesn't so I expect it is still something related to the plugin config. ๐Ÿคฆ

mnajdova avatar Nov 25 '21 15:11 mnajdova

I don't think I will have much more time to spend on this, but if someone from the community wants to help I can provide some guidance.

mnajdova avatar Nov 26 '21 09:11 mnajdova

I don't think I will have much more time to spend on this, but if someone from the community wants to help I can provide some guidance.

@mnajdova thanks for looking into it! Just had a busy week at work myself, I'll look into what you've done over the weekend and might touch base if you don't mind.

cjmcintyre avatar Nov 26 '21 10:11 cjmcintyre

@mnajdova thanks for looking into it! Just had a busy week at work myself, I'll look into what you've done over the weekend and might touch base if you don't mind.

Sure, feel free to shoot me a message on Twitter for fastest response.

mnajdova avatar Nov 26 '21 14:11 mnajdova

@mnajdova you are welcome

gregberge avatar Nov 28 '21 20:11 gregberge

I can get it to work with the following modifications:

  1. Make sure to use dependencies as per https://github.com/mui-org/material-ui/issues/29742#issuecomment-978003198:
https://pkg.csb.dev/mui-org/material-ui/commit/97b8bd28/@mui/material
https://pkg.csb.dev/mui-org/material-ui/commit/97b8bd28/@mui/styled-engine-sc
  1. styled imports within @mui/material are defined as
import styled, { rootShouldForwardProp } from '../styles/styled';

therefore, we must make sure babel-plugin-styled-components can identify '../styles/styled' as a styled function import. So update .babelrc with:

{
  "presets": ["next/babel"],
  "plugins": [
    [
      "babel-plugin-styled-components",
      {
        "ssr": true,
        "topLevelImportPaths": [
          "@mui/material",
          "@mui/material/*",
          "@mui/system",
          "@mui/styled-engine-sc",
          "\\.\\./styles/styled"
        ]
      }
    ]
  ]
}
  1. For server bundles, Next.js prefers the package.json main field over the module field. This makes it import the commonjs version of the components. They are compiled from source and their styled imports look like
var _styled = _interopRequireDefault(require("styled-components"));
// ...
const Button = (0, _styled.default)(/* ... */)

These also don't get picked up yet by babel-plugin-styled-components. One potential solution for this is to force the Next.js webpack resolver to always prefer module over main. That way it will use the ESM version of @mui/material on the server, which the babel plugin can transform correctly. Caution, this will apply to all modules and may break your project.

// next.config.js
const withTM = require("next-transpile-modules")([
  "@mui/material",
  "@mui/system",
  "@mui/styled-engine",
  "@mui/styled-engine-sc",
]); // pass the modules you would like to see transpiled

module.exports = withTM(
  /** @type {import('next').NextConfig} */ ({
    reactStrictMode: true,
    webpack: (config, { isServer }) => {
      config.resolve.alias = {
        ...config.resolve.alias,
        "@mui/styled-engine": "@mui/styled-engine-sc",
      };

      if (isServer) {
        config.resolve.mainFields = ["module", "main"];
      }

      return config;
    },
  })
);

I've put it all together in this updated sandbox I consider this setup very brittle and it significantly slows down the build times. I would recommend using emotion instead.

Janpot avatar Nov 30 '21 12:11 Janpot

@Janpot thanks. With the above I was getting error:

Warning: Prop `className` did not match. Server: "MuiSvgIcon-root-hvvBEO eVClND MuiSvgIcon-root MuiSvgIcon-fontSizeMedium SearchBarStyles__SearchIconContainer-sc-aveh8t-1 jhUKiq" Client: "MuiSvgIcon-root-ffqUiY iEhhrj MuiSvgIcon-root MuiSvgIcon-fontSizeMedium SearchBarStyles__SearchIconContainer-sc-aveh8t-1 jhUKiq"

The SVG icon came from @mui/icons-material, so I added that to the withTM array and topLevelImportPaths array. The error still persists though. (I also tried "@mui/icons-material/*")`

edit: the bug seems to only occur on running a dev server, and starts after a randon number of manual refreshes for some reason? updated sandbox

AndyW22 avatar Dec 01 '21 13:12 AndyW22

Iam not sure if this is a good workaround, but what I did is just to add &&& in every MUI overridden component.

const StyledCard = styled(Card)`
   &&& {
      background: red;
   }
`;

I know it's not good to rewrite &&& in every part of the style but it works for now

resqiar avatar Dec 29 '21 15:12 resqiar

It's been more than 3 months since v5 was officially released and there is still no way to use it with Next.js and styled-components.

Next.js is the most popular React framework and styled-components is the most popular css-in-js styling solution.

People using styled-components in their project can try to make the switch to emotion, but there are downsides to it. For instance, emotion doesn't support transient props, there is no stylelint support and no vscode plugin for syntax highlighting.

Is this Style Library Interoperability a challenge for all UI libraries? Should we expect to have a fully working and equally fast/performant Next.js + styled-components + MUI v5 example in the near future or should everyone just stops using styled-component with MUI?

CloutProject avatar Dec 30 '21 02:12 CloutProject

Since Next JS SWC compiler has been updated to work with styled component I have tried using SWC instead bable.

https://codesandbox.io/s/nextjs-ssr-with-styled-components-typescript-14exc?file=/next.config.js

seems it working fine. Better to check further

Github code : https://github.com/subodha/nextjs-with-mui-styled-components-typescript

cc: @mnajdova

subodha avatar Jan 01 '22 21:01 subodha

I've got a Next.js 12 (SWC) + MUI 5 + styled-components + TypeScript build working with the following setup:

package.json
...
"dependencies": {
  "@mui/material": "^5.2.7",
  "@mui/styled-engine": "npm:@mui/styled-engine-sc@^5.1.0",
  "@mui/styled-engine-sc": "^5.1.0",
  "next": "latest",
  "react": "latest",
  "react-dom": "latest",
  "styled-components": "^5.3.3"
},
"devDependencies": {
  "@types/node": "latest",
  "@types/react": "latest",
  "@types/styled-components": "latest",
  "next-transpile-modules": "latest",
  "typescript": "latest"
}
next.config.js
const withTM = require('next-transpile-modules')([
  '@mui/material',
  '@mui/system',
  // If @mui/icons-material is being used
  '@mui/icons-material'
]);

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  experimental: {
    styledComponents: true
  },
  webpack: (config) => {
    config.resolve.alias = {
      ...config.resolve.alias,
      '@mui/styled-engine': '@mui/styled-engine-sc'
    };
    return config;
  }
};

module.exports = withTM(nextConfig);
pages/_document.tsx

A custom document, as seen here.

import type { DocumentContext, DocumentInitialProps } from 'next/document'
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

class CustomDocument extends Document {
  public static async getInitialProps(
    ctx: DocumentContext
  ): Promise<DocumentInitialProps> {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />)
        })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        )
      }
    } finally {
      sheet.seal()
    }
  }
}

export default CustomDocument

Note: Use path imports when importing MUI, otherwise you'll get a massive bundle size. Read more here.

GitHub example: https://github.com/SebHex/next-mui-sc-ts

SebHex avatar Jan 10 '22 07:01 SebHex

Thanks, @subodha and @SebHex for sharing your examples, I was reluctant to depend on the experimental option for nextjs, but it could be our only working option. I will test out the repositories you've shared and post my update here.

mnajdova avatar Jan 11 '22 09:01 mnajdova

I have created a working example for MUI + styled-components [styled-engine-sc] + Next.js TS + SWC ๐Ÿš€ ..

https://github.com/subodha/next-ssr-ts-swc-mui-sc-example

Theme can be customized by updating src/theme.ts

It works fine for me. Feel free to share any feedback :relaxed:

subodha-atomix avatar Jan 12 '22 09:01 subodha-atomix

I have created a working example for MUI + styled-components [styled-engine-sc] + Next.js TS + SWC ๐Ÿš€ ..

https://github.com/subodha/next-ssr-ts-swc-mui-sc-example

Theme can be customized by updating src/theme.ts

It works fine for me. Feel free to share anyone feedback

@subodha This seems to be a working solution for me too, thanks for this!

SenalDolage avatar Jan 12 '22 09:01 SenalDolage

I've got a Next.js 12 (SWC) + MUI 5 + styled-components + TypeScript build working with the following setup: package.json next.config.js pages/_document.tsx

Note: Use path imports when importing MUI, otherwise you'll get a massive bundle size. Read more here.

GitHub example: https://github.com/SebHex/next-mui-sc-ts

I have created a working example for MUI + styled-components [styled-engine-sc] + Next.js TS + SWC ๐Ÿš€ ..

https://github.com/subodha/next-ssr-ts-swc-mui-sc-example

Theme can be customized by updating src/theme.ts

It works fine for me. Feel free to share anyone feedback

@subodha-atomix @SebHex Sorry but neither of these examples are solving the issue as you are not actually using styled components anywhere in the repo. Please refer to this comment which explains what the issue is. This is the same problem the material ui example repo has, the problem is not setting up styled components and being able to build. The problem is that actually using styled components with material ui doesn't work. for example:

import styled from 'styled-components';
import Paper from '@mui/material/Paper';


export const StyledPaper = styled(Paper)`
background-color: blue;
`

I have tried with SWC and the same issue occurs. It works fine with next start, but next dev doesn't work, the styles will change after 1-2 reloads and you have to constantly restart the dev server or do next start to see what the styles will actually look like in prod making developing styles tedious.

AndyW22 avatar Jan 12 '22 09:01 AndyW22

I've got a Next.js 12 (SWC) + MUI 5 + styled-components + TypeScript build working with the following setup: package.json next.config.js pages/_document.tsx Note: Use path imports when importing MUI, otherwise you'll get a massive bundle size. Read more here. GitHub example: https://github.com/SebHex/next-mui-sc-ts

I have created a working example for MUI + styled-components [styled-engine-sc] + Next.js TS + SWC ๐Ÿš€ .. https://github.com/subodha/next-ssr-ts-swc-mui-sc-example Theme can be customized by updating src/theme.ts It works fine for me. Feel free to share anyone feedback

@subodha-atomix @SebHex Sorry but neither of these examples are solving the issue as you are not actually using styled components anywhere in the repo. Please refer to this comment which explains what the issue is. This is the same problem the material ui example repo has, the problem is not setting up styled components and being able to build. The problem is that actually using styled components with material ui doesn't work. for example:

import styled from 'styled-components';
import Paper from '@mui/material/Paper';


export const StyledPaper = styled(Paper)`
background-color: blue;
`

I have tried with SWC and the same issue occurs. It works fine with next start, but next dev doesn't work, the styles will change after 1-2 reloads and you have to constantly restart the dev server or do next start to see what the styles will actually look like in prod making developing styles tedious.

Hi @AndyW22

Have you tried with @mui/system styled instead using styled from 'styled-components';

import { styled } from '@mui/system';

const TypographyStyled = styled(Typography)`
  color: white;
  margin-left: 12px;
` 

I updated the repo here. please do let me know is the issue is still there

https://github.com/subodha/next-ssr-ts-swc-mui-sc-example/blob/main/src/pages/index.tsx#L18

subodha avatar Jan 12 '22 10:01 subodha

I've got a Next.js 12 (SWC) + MUI 5 + styled-components + TypeScript build working with the following setup: package.json next.config.js pages/_document.tsx Note: Use path imports when importing MUI, otherwise you'll get a massive bundle size. Read more here. GitHub example: https://github.com/SebHex/next-mui-sc-ts

I have created a working example for MUI + styled-components [styled-engine-sc] + Next.js TS + SWC ๐Ÿš€ .. https://github.com/subodha/next-ssr-ts-swc-mui-sc-example Theme can be customized by updating src/theme.ts It works fine for me. Feel free to share anyone feedback

@subodha-atomix @SebHex Sorry but neither of these examples are solving the issue as you are not actually using styled components anywhere in the repo. Please refer to this comment which explains what the issue is. This is the same problem the material ui example repo has, the problem is not setting up styled components and being able to build. The problem is that actually using styled components with material ui doesn't work. for example:

import styled from 'styled-components';
import Paper from '@mui/material/Paper';


export const StyledPaper = styled(Paper)`
background-color: blue;
`

I have tried with SWC and the same issue occurs. It works fine with next start, but next dev doesn't work, the styles will change after 1-2 reloads and you have to constantly restart the dev server or do next start to see what the styles will actually look like in prod making developing styles tedious.

Hi @AndyW22

Have you tried with @mui/system styled instead using styled from 'styled-components';

import { styled } from '@mui/system';

const TypographyStyled = styled(Typography)`
  color: white;
  margin-left: 12px;
` 

I updated the repo here. please do let me know is the issue is still there

https://github.com/subodha/next-ssr-ts-swc-mui-sc-example/blob/main/src/pages/index.tsx#L18

i tried running the server from that repo, but it gives:

error - ./node_modules/@mui/system/esm/ThemeProvider/ThemeProvider.js:5:0
Module not found: Can't resolve '@mui/styled-engine'

AndyW22 avatar Jan 12 '22 10:01 AndyW22

I've got a Next.js 12 (SWC) + MUI 5 + styled-components + TypeScript build working with the following setup: package.json next.config.js pages/_document.tsx Note: Use path imports when importing MUI, otherwise you'll get a massive bundle size. Read more here. GitHub example: https://github.com/SebHex/next-mui-sc-ts

I have created a working example for MUI + styled-components [styled-engine-sc] + Next.js TS + SWC ๐Ÿš€ .. https://github.com/subodha/next-ssr-ts-swc-mui-sc-example Theme can be customized by updating src/theme.ts It works fine for me. Feel free to share anyone feedback

@subodha-atomix @SebHex Sorry but neither of these examples are solving the issue as you are not actually using styled components anywhere in the repo. Please refer to this comment which explains what the issue is. This is the same problem the material ui example repo has, the problem is not setting up styled components and being able to build. The problem is that actually using styled components with material ui doesn't work. for example:

import styled from 'styled-components';
import Paper from '@mui/material/Paper';


export const StyledPaper = styled(Paper)`
background-color: blue;
`

I have tried with SWC and the same issue occurs. It works fine with next start, but next dev doesn't work, the styles will change after 1-2 reloads and you have to constantly restart the dev server or do next start to see what the styles will actually look like in prod making developing styles tedious.

Hi @AndyW22 Have you tried with @mui/system styled instead using styled from 'styled-components';

import { styled } from '@mui/system';

const TypographyStyled = styled(Typography)`
  color: white;
  margin-left: 12px;
` 

I updated the repo here. please do let me know is the issue is still there https://github.com/subodha/next-ssr-ts-swc-mui-sc-example/blob/main/src/pages/index.tsx#L18

i tried running the server from that repo, but it gives:

error - ./node_modules/@mui/system/esm/ThemeProvider/ThemeProvider.js:5:0
Module not found: Can't resolve '@mui/styled-engine'

Hi @AndyW22

You have to add install @mui/styled-engine-sc manually I have mentioned it on the readme file. Do let me know if you have any issues after that

subodha avatar Jan 12 '22 10:01 subodha

You have to add install @mui/styled-engine-sc manually

Why would this be required? It doesn't even produce any changes in package.json?

mnajdova avatar Jan 12 '22 11:01 mnajdova

You have to add install @mui/styled-engine-sc manually

Why would this be required? It doesn't even produce any changes in package.json?

It didn't install via yarn install even it is on the package json. I'm working on that @mnajdova

subodha avatar Jan 12 '22 11:01 subodha

@subodha I've replaced the code from https://codesandbox.io/s/wandering-sunset-3x4xd?file=/src/Copyright.tsx:0-427 using two pages and I manage to break it after the first edit of a page.

mnajdova avatar Jan 12 '22 11:01 mnajdova

@subodha we had a similar setup, but needed to revert it, see https://github.com/mui-org/material-ui/pull/27917 as an example

mnajdova avatar Jan 12 '22 11:01 mnajdova

https://codesandbox.io/s/wandering-sunset-3x4xd?file=/src/Copyright.tsx:0-427

I will check on this

subodha avatar Jan 12 '22 11:01 subodha

I've updated https://github.com/mui-org/material-ui/pull/29873 to also add withConfig internally on all MUI components, but still, it doesn't solve the issue. I will extract the changes that are necessary for the plugin to work and will continue iterating on that PR. If someone wants to give a try on the latest packages build there these are the packages you will need:

"@mui/material": "https://pkg.csb.dev/mui-org/material-ui/commit/133bb5f0/@mui/material",
"@mui/styled-engine-sc": "https://pkg.csb.dev/mui-org/material-ui/commit/133bb5f0/@mui/styled-engine-sc", 

mnajdova avatar Jan 12 '22 13:01 mnajdova

@subodha thanks I was able to get my app to work with @mui/system . there are a few problems I've noticed:

  • Using react-material-ui-form-validator The inputs have a really short height for some reason, and aren't fixed by any style changes. If i import a <TextField /> , then that will fix the styling of all the inputs, even though I'm not using the <TextField />, it breaks again if I try and style the TextField.
  • @mui/system doesnt work for styled html ie divs, so I need to use both styled from styled-components and mui/system for different components, making the build size bigger and the app more complex
  • Building is very slow
  • Have to install styled-engine-sc whenever a module changes or else it will fail build
  • Updating styles on dev server doesn't always do anything, I have to restart the dev server to see the changes sometimes. It also takes a long time to update.
  • Sometimes on the dev server the mui components lose the color props, ie if the component has color="inherit" it will change to primary.
  • the colour on the Paper components is wrong, it's never the same as what I set it as. Always has a slightly different colour.

All in all, it seems the current solution involves a lot of hacks and workarounds that for me just aren't worth the mui v5 improvements. Even with the hacks, it still doesn't work correctly. For now I suggest using mui v4 until there is a fully working solution.

AndyW22 avatar Jan 12 '22 13:01 AndyW22

All in all, it seems the current solution involves a lot of hacks and workarounds that for me just aren't worth the mui v5 improvements. Even with the hacks, it still doesn't work correctly. For now I suggest using mui v4 until there is a fully working solution.

@AndyW22 why don't you use the default styled engine - emotion? There aren't any known problem with it. You can still use the styled() from @mui/system. Even in v4, material-ui doesn't come with build in styled-components support. Note that you can still use styled-components for overriding when using the default styled engine, the problem is that you would need to have both styling engines in the bundle (which I suppose is a problem that you already have, in case if you use v4 with styled-components).

mnajdova avatar Jan 12 '22 15:01 mnajdova

All in all, it seems the current solution involves a lot of hacks and workarounds that for me just aren't worth the mui v5 improvements. Even with the hacks, it still doesn't work correctly. For now I suggest using mui v4 until there is a fully working solution.

@AndyW22 why don't you use the default styled engine - emotion? There aren't any known problem with it. You can still use the styled() from @mui/system. Even in v4, material-ui doesn't come with build in styled-components support. Note that you can still use styled-components for overriding when using the default styled engine, the problem is that you would need to have both styling engines in the bundle (which I suppose is a problem that you already have, in case if you use v4 with styled-components).

my app is quite deeply vested into styled components so I haven't really been considering switching over to emotion. Looking at the documentation it looks very similar though, so maybe I'll change to emotion if I get round to it.

AndyW22 avatar Jan 12 '22 15:01 AndyW22

@subodha I've replaced the code from https://codesandbox.io/s/wandering-sunset-3x4xd?file=/src/Copyright.tsx:0-427 using two pages and I manage to break it after the first edit of a page.

hi @mnajdova the main difference I could find is _document.tsx Our one is https://codesandbox.io/s/nextjs-ssr-with-styled-components-typescript-14exc?file=/pages/_document.tsx

subodha avatar Jan 12 '22 17:01 subodha

I've got a Next.js 12 (SWC) + MUI 5 + styled-components + TypeScript build working with the following setup: package.json next.config.js pages/_document.tsx Note: Use path imports when importing MUI, otherwise you'll get a massive bundle size. Read more here. GitHub example: https://github.com/SebHex/next-mui-sc-ts

@subodha-atomix @SebHex Sorry but neither of these examples are solving the issue as you are not actually using styled components anywhere in the repo. Please refer to this comment which explains what the issue is. This is the same problem the material ui example repo has, the problem is not setting up styled components and being able to build. The problem is that actually using styled components with material ui doesn't work. for example:

import styled from 'styled-components';
import Paper from '@mui/material/Paper';


export const StyledPaper = styled(Paper)`
background-color: blue;
`

I have tried with SWC and the same issue occurs. It works fine with next start, but next dev doesn't work, the styles will change after 1-2 reloads and you have to constantly restart the dev server or do next start to see what the styles will actually look like in prod making developing styles tedious.

Hey @AndyW22

My build seems to be working fine for me. Using both npm run dev and npm run build && npm run start works as expected.

I also added more example usages based on what you said. Let me know if you're still having issues with my build or want me to add more examples ๐Ÿ˜Š

image

Commit: https://github.com/SebHex/next-mui-sc-ts/commit/8829168405991cfee79bd6f2f2fc93155487c3e4

SebHex avatar Jan 13 '22 02:01 SebHex

  • [email protected] (not latest)
  • const withTM = require('next-transpile-modules')(['@mui/material', '@mui/lab', '@mui/system']); in next.config.js
  • experimental: { styledComponents: true,}, in next.config.js

seems to fix my case, but I cannot be sure. I want it to be fixed without complex settings.

kondei avatar Jan 26 '22 11:01 kondei

styled-components issue says that some SSR problems were fixed since 5.3.1. But it seems to break some styles since 5.3.1 with MUI & next.js build. I am confused.

https://github.com/styled-components/styled-components/issues/3482

kondei avatar Jan 26 '22 11:01 kondei

I am facing the same issue. Is there anything one can do to fix it in the meantime?

kdelmonte avatar Mar 01 '22 01:03 kdelmonte

@kdelmonte we haven't find any solution to this problem yet, and it looks like there is no response to:

  • https://github.com/styled-components/babel-plugin-styled-components/pull/364
  • https://github.com/styled-components/babel-plugin-styled-components/pull/365 My honest proposal would be to switch to emotion using the default styled-engine. The migration should be pretty much straight forward.

mnajdova avatar Mar 02 '22 11:03 mnajdova

Thank you @mnajdova. I migrated yesterday to emotion because I could not wait anymore and like you say, the migration was pretty easy. Thanks again.

kdelmonte avatar Mar 02 '22 12:03 kdelmonte

Sure thing @kdelmonte, and sorry for the delayed answer.

mnajdova avatar Mar 02 '22 12:03 mnajdova

@kdelmonte we haven't find any solution to this problem yet, and it looks like there is no response to:

I have a PR up to fix https://github.com/styled-components/babel-plugin-styled-components/pull/365: https://github.com/styled-components/babel-plugin-styled-components/pull/380

However I haven't made a fix for https://github.com/styled-components/babel-plugin-styled-components/pull/364. The second test case already works. I'm not sure if the first test case should be fixed. It seems like styled-components intentionally ignores renamed imports of styled because of https://github.com/styled-components/babel-plugin-styled-components/issues/224.

rbong avatar Jul 30 '22 18:07 rbong

@rbong I haven't been looking into this for quite some time. I can try to refresh my view on it next week and provide more feedback if I can. Thanks a lot for the effort put there ๐Ÿ™

mnajdova avatar Aug 05 '22 12:08 mnajdova