Not working with MUI
fenos opened this issue · comments
Hello,
I've installed vavite to benefit from it's nicer developer experience.
The problem is that I haven't managed to make the production build work with MUI v5.10
Everything compiles just fine, however when I visit the localhost page it returns this error:
import { red } from "@mui/material/colors/index.js";
^^^
SyntaxError: Named export 'red' not found. The requested module '@mui/material/colors/index.js' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from '@mui/material/colors/index.js';
const { red } = pkg;
I'm using vite-ssr-plugin
as the server-side renderer and here are the steps to reproduce the issue by using the examples/vite-ssr-plugin
-
Install MUI
npm install @mui/material @emotion/react @emotion/styled -S
-
Import the colors package
import {red} from "@mui/material/colors/index"
inpage/about.tsx
-
Use the color in the dom:
${red.A100}
-
Compile the project by using
vavita
-
run the serer
node dist/server/index.js
-
visit: http://localhost:3000
You should see the exact same error
do you have any tips?
Thanks!
Hi!
This is an unfortunate result of the way MUI is packaged: Deep imports are problematic because they have the .js
extension but they're in ESM format and they don't have "type": "module"
in their package.json
. This won't work using Node's native ESM either.
The easiest solution is not to use deep imports and rely on tree-shaking:
import { colors } from "@mui/material";
// And then use colors.red
Here's a working example: https://stackblitz.com/edit/github-f7eedh?file=pages/index/index.page.tsx
If, for some reason, you can't live with that, you can tell Vite to process imports from "@mui/material"
instead of trying to import them directly during SSR by adding ssr: { noExternal: ["@mui/material"] }
to your config. You will get some warnings about unused imports during the build but they seem to be benign.