GitLab Pages部署Vite应用遇白屏及MIME类型错误求助
问题描述
我尝试在GitLab Pages部署Vite应用,但页面仅显示白屏,且出现如下错误:无法加载static目录下的CSS和JS文件,因MIME类型(“text/html”)不匹配被拦截(X-Content-Type-Options: nosniff)。已查阅Vite相关配置但均未解决问题,求解决思路。
我的配置文件
vite.config.js
import { fileURLToPath, URL } from 'node:url' import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ vue(), ], define: { 'process.env': {} }, resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } }, base: './', })
gitlab-ci.yml
pages: image: node:latest stage: deploy cache: key: files: - package-lock.json prefix: npm paths: - node_modules/ script: - npm install - npm run build - rm -rf public - mkdir public - cp -r dist/* public artifacts: paths: - public only: - main
打包后生成的index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vite App</title> <script type="module" crossorigin src="/assets/index-daca0686.js"></script> <link rel="modulepreload" crossorigin href="/assets/bootstrap.bundle-71906194.js"> <link rel="stylesheet" href="/assets/bootstrap-eafa8fec.css"> </head> <body> <div id="app"></div> </body> </html>
解决思路
修正Vite的base配置
当前设置的base: './'不符合GitLab Pages的路径规则。GitLab Pages的资源路径基于项目仓库名的绝对路径,比如你的Pages地址是https://<用户名>.gitlab.io/<项目仓库名>/,必须将base设置为'/<项目仓库名>/'。修改
vite.config.js中的base配置:base: '/你的项目仓库名/',例如仓库名为
vite-gitlab-demo,则写成base: '/vite-gitlab-demo/'。重新打包后,index.html中的资源路径会自动带上项目路径前缀,确保请求能正确指向public目录下的资源文件。验证资源路径与文件存在性
在gitlab-ci.yml的脚本中添加ls -la dist命令,确认打包后的dist目录下存在assets文件夹及对应的JS/CSS文件:script: - npm install - npm run build - ls -la dist # 新增这行,查看打包结果 - rm -rf public - mkdir public - cp -r dist/* public如果dist目录结构异常,检查Vite打包配置是否有其他冲突项。
排除路由模式影响(若使用Vue Router)
若你的项目使用了Vue Router的history模式,需要在GitLab Pages中配置重定向规则:在public目录下创建_redirects文件,内容为/* /index.html 200,确保所有路由请求都指向index.html,避免路由跳转后资源路径错误。
内容的提问来源于stack exchange,提问作者Shinzie

