Search code examples
javascriptreactjsbuildmaterial-uivite

Vite build: Uncaught TypeError: Cannot read properties of null (reading 'useContext')


I imported this component from material-ui : import Paper from '@mui/material/Paper';

When i run npm run build then npm run preview i got this error in the console :
Uncaught TypeError: Cannot read properties of null (reading 'useContext').

This is the example code i use it.

Note: when i run the app with npm run dev it works fine.


Solution

  • I figured out that including @mui/material in vite.config.js and destructuring Paper from @mui/material will solve my issue.

    in vite.config.js:

    export default defineConfig({
      //...
      optimizeDeps: {
        //... 
        include: [
          "@mui/material"
          // include other packages that may broke the build
        ]
     }
    });
    

    in the component:

    import {Paper, otherComponents...} from '@mui/material'