如何将Vite React项目默认运行在http://localhost:3000而非127.0.0.1:5173
解决Vite React项目默认启动localhost:3000的问题
可行解决方案
1. 明确指定打开的URL
在vite.config.js中添加open选项,强制浏览器打开目标地址,确保配置生效:
import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; export default defineConfig({ plugins: [react()], server: { host: "localhost", port: 3000, open: "http://localhost:3000" }, });
2. 检查package.json的dev命令
确保dev命令没有覆盖配置参数,避免出现类似--host 127.0.0.1或--port 5173的强制参数。正确的dev命令应为:
{ "scripts": { "dev": "vite" } }
3. 清除Vite缓存
Vite缓存可能导致旧配置残留,按以下步骤操作:
- 关闭正在运行的开发服务
- 删除项目根目录下的
node_modules/.vite文件夹 - 重新执行
npm run dev
4. 验证hosts文件(可选)
确认系统hosts文件中localhost指向127.0.0.1:
- Windows:编辑
C:\Windows\System32\drivers\etc\hosts - macOS/Linux:编辑
/etc/hosts
确保存在该行:127.0.0.1 localhost,若缺失则添加(需管理员权限)。
5. 命令行直接指定参数(临时方案)
如果上述方法无效,可在package.json的dev命令中直接指定参数:
{ "scripts": { "dev": "vite --host localhost --port 3000" } }
内容的提问来源于stack exchange,提问作者Gagan
相关产品推荐
相关产品推荐

