Vite React应用部署Cloudflare Pages构建失败:路径解析错误求助
解决Vite React应用部署Cloudflare Pages的路径解析错误问题
问题根源
你配置的别名src: "/src"是系统绝对路径,本地开发时因项目根目录为当前工作目录可正常生效,但Cloudflare Pages构建环境中项目代码存放在/opt/buildhome/repo/下,/src会被解析为系统根目录的src文件夹,而非项目根目录下的src,导致Rollup无法定位目标文件。
解决方案
1. 修正Vite配置文件的别名
使用Node.js的path模块解析项目根目录下的src路径,确保在任何环境下都指向正确位置:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import path from 'path'; export default defineConfig({ plugins: [react()], resolve: { alias: { // 推荐使用@作为别名,也可保留src(需同步后续配置) '@': path.resolve(__dirname, './src'), // 若保留src别名则改为: // src: path.resolve(__dirname, './src'), }, }, });
2. 配置编辑器/编译器路径映射
创建jsconfig.json(JS项目)或tsconfig.json(TS项目),让IDE和构建工具都能识别别名:
jsconfig.json示例:
{ "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["src/*"] // 对应src别名的配置: // "src/*": ["src/*"] } }, "include": ["src"] }
tsconfig.json示例:
{ "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["src/*"] } }, "include": ["src"] }
3. 修正代码中的导入语句
将原绝对路径导入改为别名导入:
- 错误写法:
import Snackbar from "/src/components/Snackbar" - 修改后(对应@别名):
import Snackbar from "@/components/Snackbar"
或(对应src别名):import Snackbar from "src/components/Snackbar"
4. 确认Cloudflare Pages构建配置
确保构建命令设置为npm run build,Cloudflare默认会将NODE_ENV设为production,无需额外配置。
验证
本地重新执行npm run build确认正常,再推送代码触发Cloudflare Pages构建即可解决路径解析错误。
内容的提问来源于stack exchange,提问作者Maarten
相关产品推荐
相关产品推荐

