Vue 3 项目静态文件打包后出现 404 问题,通常有以下几种解决方案:
一、路径配置问题(最常见)
1. 配置 vue.config.js
// vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
// 或者使用相对路径
// publicPath: '/your-project-name/', // 如果是部署在子路径下
assetsDir: 'static',
filenameHashing: true,
// 如果需要自定义输出目录结构
chainWebpack: config => {
config.module
.rule('images')
.set('parser', {
dataUrlCondition: {
maxSize: 4 * 1024 // 4kb
}
})
}
})
2. Vite 项目配置
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
base: './', // 使用相对路径
// base: '/project-name/', // 子路径部署
build: {
outDir: 'dist',
assetsDir: 'assets',
rollupOptions: {
output: {
chunkFileNames: 'js/[name]-[hash].js',
entryFileNames: 'js/[name]-[hash].js',
assetFileNames: '[ext]/[name]-[hash].[ext]'
}
}
}
})
二、路由模式问题
1. History 模式问题
如果是 history 模式,需要在服务器配置 fallback:
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
// history: createWebHistory(), // 需要服务器配置
history: createWebHistory('/your-project/'), // 子路径部署
// 或使用 hash 模式(无需服务器配置)
// history: createWebHashHistory(),
routes: [...]
})
2. 服务器配置示例
Nginx:
location / {
try_files $uri $uri/ /index.html;
}
# 子路径部署
location /your-project/ {
alias /path/to/your/dist/;
try_files $uri $uri/ /your-project/index.html;
}
Apache:
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
三、静态资源引用方式
1. 正确的引用方式
<!-- 模板中使用 -->
<template>
<!-- 使用相对路径 -->
<img src="./assets/logo.png" alt="">
<!-- 或使用绝对路径 -->
<img src="/src/assets/logo.png" alt="">
<!-- 或使用 require -->
<img :src="require('./assets/logo.png')" alt="">
</template>
<script setup>
// JS中使用
import logo from '@/assets/logo.png'
const imageUrl = new URL('./assets/logo.png', import.meta.url).href
</script>
<style scoped>
/* CSS中使用 */
.background {
background-image: url('./assets/bg.jpg');
/* 或使用 @import */
}
</style>
四、环境变量配置
// .env.production
VUE_APP_PUBLIC_PATH=./
// 在代码中使用
const publicPath = process.env.VUE_APP_PUBLIC_PATH || '/'
五、完整的部署检查清单
检查 publicPath 配置
验证服务器配置
清除浏览器缓存
检查构建输出结构
使用正确的 URL 访问
检查资源引用路径
六、快速诊断命令
# 1. 构建并检查输出
npm run build
ls -la dist/
# 2. 本地预览构建结果
npm install -g serve
serve dist -s # 单页应用模式
# 3. 检查路径是否正确
cat dist/index.html | grep -E "(src|href)="
七、常见问题排查
按出现频率,建议按以下顺序排查:
publicPath 配置
服务器配置
路由模式
资源引用方式
选择哪种方案取决于你的部署环境和项目结构。最通用的方案是配置正确的 publicPath 和服务器路由回退。