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

Vue3 + Vite项目npm run build构建不完整问题求助

Vue3 + Vite 构建异常问题解决方案

1. 修复本地打开index.html空白与路径问题

本地打开打包后的index.html空白,核心是路径配置问题。修改vite.config.js,添加base配置适配相对路径:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  base: './', // 本地打开用相对路径,部署到服务器子目录时改为'/你的子目录名/'
  build: {
    assetsDir: 'assets', // 指定资源统一输出到dist/assets目录
  }
})

2. 解决资源未打包问题

src/assets下的图片未被打包,大概率是引用方式错误,按以下两种正确方式引用:

  • 方式一:通过import引入
<script setup>
import logo from './assets/logo.png'
</script>
<template>
  <img :src="logo" alt="logo">
</template>
  • 方式二:使用new URL()动态生成路径
<template>
  <img :src="new URL('./assets/logo.png', import.meta.url).href" alt="logo">
</template>

如果仍有资源未打包,可在vite.config.js中明确指定资源类型:

build: {
  assetsInclude: ['**/*.png', '**/*.jpg', '**/*.svg', '**/*.webp']
}

3. 修复路由跳转报错

路由跳转报错多是history模式的服务器配置问题,优先用hash模式快速验证:

import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(), // 替换createWebHistory,无需服务器额外配置
  routes: [/* 你的路由列表 */]
})

若要坚持history模式,服务器需配置 fallback到index.html(以Nginx为例):

location / {
  try_files $uri $uri/ /index.html;
}

4. 拆分打包文件(解决单js/单css问题)

想要生成多个拆分后的js/css文件,在vite.config.js的build.rollupOptions中配置代码拆分规则:

build: {
  rollupOptions: {
    output: {
      manualChunks: {
        vue: ['vue'], // 把vue核心库拆成单独文件
        router: ['vue-router'], // 路由相关代码单独拆分
        utils: ['./src/utils'] // 自定义工具类单独拆分
      }
    }
  }
}

内容的提问来源于stack exchange,提问作者Sergio Sanchez-Alvares

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:07:09