mui / material-ui

Material UI: Ready-to-use foundational React components, free forever. It includes Material UI, which implements Google's Material Design.
https://mui.com/material-ui/
MIT License
91.86k stars 31.57k forks source link

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

Open zibra opened 2 years ago

zibra commented 2 years ago

Duplicates

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 commented 2 years ago

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 commented 2 years ago

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

zibra commented 2 years ago

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

cjmcintyre commented 2 years ago

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

zibra commented 2 years ago

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

cjmcintyre commented 2 years ago

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.

AndyW22 commented 2 years ago

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.

cjmcintyre commented 2 years ago

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.

AndyW22 commented 2 years ago

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.

mnajdova commented 2 years ago

I will look more into this tomorrow and post my findings

mnajdova commented 2 years ago

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 commented 2 years ago

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

mnajdova commented 2 years ago

Similar issues found on the styled-components repo:

pedroeckel commented 2 years ago

I have the same problem on my project

mnajdova commented 2 years ago

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 commented 2 years ago

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.

cjmcintyre commented 2 years ago

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.

mnajdova commented 2 years ago

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

gregberge commented 2 years ago

@mnajdova you are welcome

Janpot commented 2 years ago

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
  2. 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"
        ]
      }
    ]
    ]
    }
  3. 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](https://codesandbox.io/s/reverent-jennings-ixgfq)
I consider this setup very brittle and it significantly slows down the build times. I would recommend using emotion instead.
AndyW22 commented 2 years ago

@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

resqiar commented 2 years ago

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

CloutProject commented 2 years ago

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?

subodha commented 2 years ago

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

SebHex commented 2 years ago

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

package.json ```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 ```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](https://nextjs.org/docs/advanced-features/custom-document), as seen [here](https://github.com/vercel/next.js/blob/canary/examples/with-typescript-styled-components/pages/_document.tsx). ```tsx 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 { const sheet = new ServerStyleSheet() const originalRenderPage = ctx.renderPage try { ctx.renderPage = () => originalRenderPage({ enhanceApp: (App) => (props) => sheet.collectStyles() }) 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

mnajdova commented 2 years ago

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.

subodha-atomix commented 2 years ago

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:

SenalDolage commented 2 years ago

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!

AndyW22 commented 2 years ago

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.

subodha commented 2 years ago

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

AndyW22 commented 2 years ago

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'
subodha commented 2 years ago

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

mnajdova commented 2 years ago

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?

subodha commented 2 years ago

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

mnajdova commented 2 years ago

@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 commented 2 years ago

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

subodha commented 2 years ago

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

I will check on this

mnajdova commented 2 years ago

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", 
AndyW22 commented 2 years ago

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

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.

mnajdova commented 2 years ago

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

AndyW22 commented 2 years ago

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.

subodha commented 2 years ago

@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

SebHex commented 2 years ago

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

kondei commented 2 years ago

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

kondei commented 2 years ago

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

kdelmonte commented 2 years ago

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

mnajdova commented 2 years ago

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

kdelmonte commented 2 years ago

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.

mnajdova commented 2 years ago

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

rbong commented 1 year ago

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