Reputation: 31
I am having issue which says Uncaught ReferenceError: require is not defined. I am using React 18, Vite version 5. I implemented Vite to my existing React project. Everything working in dev, but when I build and deploy it into production, I am having this error. Can anyone help me with it?
I searched everywhere but no success.
Screenshot for folder structure
Screenshot for the package.json
Upvotes: 1
Views: 3255
Reputation: 3626
When using Vite, use the import
syntax instead of require()
// const react = require('react') ❌
import react from 'react' ✅
Also, when including images, svgs and videos, replace the require()
you used to use in create-react-app with the actual path of the asset file.
Example:
// # create-react-app
<img src={require('../media/myImage.png')} /> ❌
// # Vite
<img src="../media/myImage.png" /> ✅
Sometimes, in your code, you import the assets as modules:
import myImage from './myImage'
The same happens in Vite.
This is useful when you use path aliases, for instance, sometimes, you import the images in create-react-app like this:
<img src={require('@media/myImage.png')} />
In vite, if you wanted that, import it first at the top then use it at the bottom:
import MyImage from '@media/myImage.png'
<img src={MyImage} /> ✅
// <img src={"@media/myImage.png"} /> ❌
Summary: there's nothing called require()
in vite, if you used to do that in create-react-app, it can't happen in Vite.
Upvotes: 2