Skip to content

Mui with styled-components and Vite/Vitest is not working since v7 #46586

@woodreamz

Description

@woodreamz

Steps to reproduce

After migrating to mui v7, the unit tests running on Vitest are not working anymore:

Steps:

  1. Open this link to live example: https://stackblitz.com/~/github.com/woodreamz/mui7-scStyled-issue (or https://github.com/woodreamz/mui7-scStyled-issue)
  2. Run npm install
  3. Run npm run test

Current behavior

This error appears:

Image

Expected behavior

It should work like mui 6.

Context

I am using Vite + Vitest with Mui7 and styled-components. I usually use pnpm but to simplify the thing, I used npm. By the way the Using styled-components is not accurate when you work with Vite + Vitest, you must also override styled-engine in the package.json otherwise vitest resolves styled-engine instead of styled-engine-sc.

There is a workaround to make it work. You need to add the fallbackCJS this in your vite.config.ts:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";

// https://vite.dev/config/
export default defineConfig({
  test: {
    environment: "jsdom",
    globals: true,
    // #region Uncomment this code to work with Mui v7+
    server: {
      deps: {
        fallbackCJS: true,
      },
    },
    // #endregion
  },
  plugins: [react(), tsconfigPaths()],
});

I also have a premium license, I don't know if it's required for the mui support.

Thank you!

Your environment

npx @mui/envinfo
System:
    OS: macOS 14.1.1
  Binaries:
    Node: 22.16.0 - ~/.nvm/versions/node/v22.16.0/bin/node
    npm: 10.9.2 - ~/.nvm/versions/node/v22.16.0/bin/npm
    pnpm: 9.9.0 - ~/Library/pnpm/pnpm
  Browsers:
    Chrome: 138.0.7204.158
    Edge: Not Found
    Safari: 17.1
  npmPackages:
    @mui/core-downloads-tracker:  7.2.0 
    @mui/material: ^7.2.0 => 7.2.0 
    @mui/private-theming:  7.2.0 
    @mui/styled-engine-sc:  7.2.0 
    @mui/system:  7.2.0 
    @mui/types:  7.4.4 
    @mui/utils:  7.2.0 
    @types/react: ^19.1.8 => 19.1.8 
    react: ^19.1.0 => 19.1.0 
    react-dom: ^19.1.0 => 19.1.0 
    styled-components: ^6.1.19 => 6.1.19 
    typescript: ~5.8.3 => 5.8.3 

Search keywords: vitest mui7 styled-components

Metadata

Metadata

Assignees

Labels

package: systemSpecific to @mui/systemstatus: waiting for maintainerThese issues haven't been looked at yet by a maintainerviteAnything related to integration with Vite

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions