React Vite: npm run dev and npm run preview work but build shows TypeError on Render platform
I have a Django REST Framework (backend) + Postgresql + Vite React (frontend) Project which is working fine in local when I run the npm run dev command.
Here is my package.json file:
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"engines" : {
"node" : ">=21.6.2 <22.0.0"
},
"dependencies": {
"@ant-design/icons": "^5.5.1",
"@emotion/react": "^11.13.3",
"@emotion/styled": "^11.13.0",
"@mui/material": "^6.1.0",
"@reduxjs/toolkit": "^2.2.7",
"axios": "^1.7.7",
"dotenv": "^16.4.7",
"leaflet": "^1.9.4",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-leaflet": "^4.2.1",
"react-paginate": "^8.2.0",
"react-redux": "^9.1.2",
"react-router-dom": "^6.26.1",
"react-router-redux": "^4.0.8",
"react-social-icons": "^6.18.0",
"redux": "^5.0.1",
"styled-components": "^6.1.13"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
"@types/leaflet": "^1.9.16",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.1",
"eslint": "^9.9.0",
"eslint-plugin-react": "^7.35.0",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
"eslint-plugin-react-refresh": "^0.4.9",
"globals": "^15.9.0",
"vite": "^5.4.14"
}
}
My vite.config.js file below:
import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import dotenv from 'dotenv'
dotenv.config()
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd());
const isDevelopment = mode === 'development'
const baseURL = isDevelopment ? env.VITE_API_BASE_URL_LOCAL : env.VITE_API_BASE_URL_DEPLOY
console.log("baseURL")
console.log(baseURL)
return {
plugins: [react()],
server: {
proxy: {
'/api': {
target: baseURL,
changeOrigin: true,
},
},
},
}
})
I deployed the Django on Render platform which works fine.
However, if build React Vite (frontend) for production using npm install && npm run build on Render platform, the page doesn't load anything but only shows a white screen and I get a JS TypeError as below screenshot:
Another screenshot shows a TypeError in index file below:
I just play around to try to find a solution. I run npm run build in frontend in local and then I run npm run preview. The React Vite connects successfully to Django backend which is deployed on Render Platform and everything works fine. See screenshots below:
For some reason, Render does not build the source code as it is build in my local machine.