You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GitLab Pages部署Vite应用遇白屏及MIME类型错误求助

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>

解决思路

  1. 修正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目录下的资源文件。

  2. 验证资源路径与文件存在性
    在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打包配置是否有其他冲突项。

  3. 排除路由模式影响(若使用Vue Router)
    若你的项目使用了Vue Router的history模式,需要在GitLab Pages中配置重定向规则:在public目录下创建_redirects文件,内容为/* /index.html 200,确保所有路由请求都指向index.html,避免路由跳转后资源路径错误。

内容的提问来源于stack exchange,提问作者Shinzie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 11:05:00