Laravel 10 Sail搭配Nuxt3与Vite:浏览器无法连接24678端口
解决Laravel Sail容器中Nuxt3 HMR连接失败与.nuxt目录异常问题
一、修复.nuxt目录生成异常问题
你提到的错误参数导致frontend目录下生成额外子目录和独立.nuxt文件夹,本质是命令参数传递时的shell解析错误。
修正run:frontend Artisan命令
改用数组形式传递命令参数,避免解析偏差,确保命令在frontend目录下正确执行:
namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\Process; class RunFrontend extends Command { protected $signature = 'run:frontend'; protected $description = 'Runs the frontend in dev mode.'; public function handle() { Process::path(base_path('frontend')) ->forever() ->run(['npm', 'run', 'dev', '--', '--host', '0.0.0.0'], function (string $type, string $output) { $this->info($output); }); } }
执行前先删除frontend目录下错误生成的子目录和.nuxt文件夹,确保从干净状态启动。
二、解决HMR WebSocket连接失败问题
Docker容器内的localhost与宿主机的localhost属于不同网络节点,需调整Vite配置适配跨网络访问。
调整nuxt.config.ts的Vite配置
修改HMR的client指向宿主机地址,同时保持server允许外部访问:
export default defineNuxtConfig({ modules: ['@nuxtjs/tailwindcss', '@pinia/nuxt', 'nuxt-icon'], runtimeConfig: { public: { baseURL: 'http://localhost' } }, vite: { server: { host: '0.0.0.0', // 允许容器外部访问开发服务器 hmr: { protocol: 'ws', host: 'localhost', // 浏览器从宿主机地址连接HMR port: 5173 // 与docker-compose映射端口保持一致 } } } })
确认Docker Compose端口映射
你的现有配置已包含正确端口映射,保持即可:
ports: - '${APP_PORT:-80}:80' - '${FRONTEND_PORT:-3000}:3000' - '${VITE_SERVER_PORT:-5173}:5173' - 24678:24678
补充环境变量配置
在Laravel的.env文件中添加Vite相关变量,确保Nuxt识别正确的开发服务器地址:
VITE_DEV_SERVER_URL=http://localhost:5173 FRONTEND_PORT=3000
三、验证步骤
- 进入Sail容器:
sail shell - 安装前端依赖:
php artisan install:frontend - 启动前端服务:
php artisan run:frontend - 浏览器访问
http://localhost:3000,查看开发者工具的WebSocket连接状态确认HMR正常。
若问题仍存在,可尝试:
- 清除Nuxt缓存:在frontend目录执行
npx nuxt clean - 重启Sail容器:
sail down && sail up -d
内容的提问来源于stack exchange,提问作者NKnuelle
相关产品推荐
相关产品推荐

