Laravel 10生产环境部署遇app.js模块加载MIME类型错误求助
问题分析与解决方案
核心错误原因
浏览器请求Vite生成的模块脚本时,服务器返回了HTML内容(通常是404页面),导致MIME类型不匹配,触发Expected a JavaScript module script but the server responded with a MIME type of "text/html"错误。以下是针对性的修复步骤:
1. 区分开发/生产环境,正确打包资源
生产环境禁止使用npm run dev,必须运行打包命令生成静态资源:
npm run build
执行后会在public/build目录生成编译后的CSS/JS文件,Laravel的Vite插件会自动加载这些资源。
2. 修正vite.config.js语法错误与冗余配置
- 替换中文引号为英文引号(原配置中
hmr.host使用了中文引号,导致语法错误) - 生产环境无需
server/hmr配置,可通过环境变量区分开发/生产配置:
import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; import laravel from 'laravel-vite-plugin'; export default defineConfig({ plugins: [ laravel({ input: [ 'resources/css/app.css', 'resources/scss/app.scss', 'resources/js/app.js', ], refresh: true, }), vue({ template: { transformAssetUrls: { base: null, includeAbsolute: false, }, }, }), ], // 仅开发环境启用server配置 server: process.env.NODE_ENV === 'development' ? { host: true, port: 5173, strictPort: true, origin: 'https://my-domain.com', // 必须带协议头 cors: { origin: "*" }, hmr: { host: 'my-domain.com', // 英文引号 }, watch: { usePolling: true, ignored: ['**/vendor/**'], }, } : {}, });
3. 调整Nginx配置,正确处理静态资源
修改docker/nginx/default.conf,确保/build路径的静态资源直接由Nginx返回,不转发到PHP:
server { listen 80; server_name my-domain.com; root /var/www/public; index index.php index.html; location / { try_files $uri $uri/ /index.php?$query_string; } # 直接响应Vite打包资源,添加缓存策略 location /build/ { try_files $uri $uri/ =404; expires 1y; add_header Cache-Control "public, immutable"; } location ~ \.php$ { fastcgi_pass app:9000; # 匹配PHP容器的FastCGI端口 fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }
4. 优化Docker生产环境配置
生产环境无需暴露Vite开发服务器端口,可移除或注释npm服务的端口映射:
services: app: container_name: app build: docker/php volumes: - .:/var/www nginx: image: nginx container_name: nginx ports: - 80:80 - 443:443 # 若启用HTTPS需添加 volumes: - .:/var/www - docker/nginx/default.conf:/etc/nginx/conf.d/default.conf working_dir: /var/www depends_on: - app db: image: mysql:8 container_name: db command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci volumes: - docker/mysql/default.cnf:/etc/mysql/conf.d/default.cnf - mysql_data:/var/lib/mysql # 生产环境建议用持久化卷 ports: - 3306:3306 environment: MYSQL_ROOT_PASSWORD: your_root_pwd MYSQL_DATABASE: your_db_name MYSQL_USER: your_db_user MYSQL_PASSWORD: your_db_pwd # 生产环境可移除npm服务,或仅在构建阶段临时使用 # npm: # image: node:alpine # container_name: node # restart: unless-stopped # tty: true # volumes: # - ./:/var/www # ports: # - "5173:5173" volumes: mysql_data: # 新增持久化卷,避免数据丢失
5. 验证Blade模板资源加载
确保模板中使用Laravel官方@vite指令加载资源,避免手动编写script标签导致路径错误:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>应用标题</title> @vite(['resources/css/app.css', 'resources/scss/app.scss', 'resources/js/app.js']) </head> <body> <!-- 页面内容 --> </body> </html>
内容的提问来源于stack exchange,提问作者Quên Dev
相关产品推荐
相关产品推荐

