Vite项目部署至Namecheap服务器出现require未定义错误求助
问题描述
使用Vite创建React+TypeScript项目,构建后部署到Namecheap服务器时,浏览器控制台报错:
ReferenceError: require is not defined
at index-a4df310d.js:682:57318
at Hu (index-a4df310d.js:345:20340)
at Tg (index-a4df310d.js:345:20798)
at Object.useState (index-a4df310d.js:345:27178)
at Ie.useState (index-a4df310d.js:9:6382)
at sie (index-a4df310d.js:682:57154)
at aie (index-a4df310d.js:682:58185)
at $y (index-a4df310d.js:345:19520)
at wm (index-a4df310d.js:347:3139)
at PP (index-a4df310d.js:347:44801)
相关配置文件:tsconfig.json:
{ "compilerOptions": { "target": "ESNext", "useDefineForClassFields": true, "lib": ["DOM", "DOM.Iterable", "ESNext"], "allowJs": false, "skipLibCheck": true, "esModuleInterop": false, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "module": "ESNext", "moduleResolution": "Node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx" }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] }
vite.config.ts:
import {defineConfig} from "vite"; import react from "@vitejs/plugin-react"; export default defineConfig({ plugins: [react()], });
解决方案
这个错误说明构建后的代码混入了Node.js环境专属的require语法,而浏览器原生不支持该语法,以下是具体解决步骤:
修改Vite构建配置,处理CommonJS依赖
在vite.config.ts中添加build.commonjsOptions配置,强制转换混合的ES模块与CommonJS模块:import {defineConfig} from "vite"; import react from "@vitejs/plugin-react"; export default defineConfig({ plugins: [react()], build: { commonjsOptions: { transformMixedEsModules: true, }, }, });调整TypeScript模块解析策略
将tsconfig.json中的moduleResolution从Node改为Bundler,适配Vite这类打包工具的模块解析规则:"moduleResolution": "Bundler",排查依赖与代码中的CommonJS语法
- 检查项目依赖是否存在仅支持CommonJS的包,尝试将其更新到支持ES模块的版本;
- 检查自有代码中是否手动使用了
require()语法,全部替换为ES模块的import语法。
重新构建并部署
执行npm run build重新构建项目,将新生成的dist目录内容部署到Namecheap服务器,清除浏览器缓存后再次测试。
内容的提问来源于stack exchange,提问作者Developer Sabbir

