feat: 更新 Vite 配置,优化资源管理和背景图像处理

This commit is contained in:
zhongyidian committed 2025-09-14 20:44:41 +08:00
1 parent 66842e9d58
commit 02ddfd0c07
11 files changed
+202 -11

No files matched your search

+167
View File
@@ -0,0 +1,167 @@
# 图片路径构建后访问解决方案
## 问题描述
在Vue 3 + Vite + TypeScript项目中,图片资源在开发环境正常显示,但构建后无法正常访问。主要问题包括:
1. CSS中的相对路径 `url('../../assets/images/xxx.png')` 在构建后无法正确解析
2. 动态生成的图片路径无法被Vite静态分析,导致图片未被包含在构建中
3. 环境变量判断逻辑不正确
## 解决方案
### 1. 使用 `import.meta.glob` 静态导入所有图片
```typescript
// src/utils/index.ts
const imageModules = import.meta.glob('../assets/images/**/*.{png,jpg,jpeg,gif,svg,webp}', {
eager: true
})
export const getStaticImage = (path: string) => {
try {
const imagePath =
path.endsWith('.png') ||
path.endsWith('.jpg') ||
path.endsWith('.jpeg') ||
path.endsWith('.gif') ||
path.endsWith('.svg') ||
path.endsWith('.webp')
? `../assets/images/${path}`
: `../assets/images/${path}.png`
const module = imageModules[imagePath]
if (module && typeof module === 'object' && 'default' in module) {
return module.default as string
}
return new URL(imagePath, import.meta.url).href
} catch (error) {
console.error('Failed to load image:', path, error)
return ''
}
}
```
### 2. 修复CSS中的图片路径
**之前(错误):**
```css
.guide-panel {
background-image: url('../../assets/images/components/box.png');
}
```
**之后(正确):**
```vue
<template>
<div class="guide-panel" :style="{ backgroundImage: getBackgroundImage('components/box') }">
</template>
<script setup>
import { getBackgroundImage } from '@/utils'
</script>
```
### 3. 优化Vite构建配置
```typescript
// vite.config.ts
export default defineConfig(({ mode }) => {
return {
// ... 其他配置
build: {
assetsDir: 'assets',
rollupOptions: {
output: {
assetFileNames: assetInfo => {
if (/\.(png|jpe?g|gif|svg|webp)$/i.test(assetInfo.name || '')) {
return `assets/images/[name]-[hash][extname]`
}
return `assets/[name]-[hash][extname]`
}
}
}
}
}
})
```
## 关键改进点
### 1. 静态分析支持
- 使用 `import.meta.glob` 确保Vite能够静态分析所有图片资源
- 所有图片在构建时被正确包含和处理
### 2. 路径统一管理
- 通过 `getStaticImage` 函数统一管理图片路径
- 支持带扩展名和不带扩展名的路径
- 提供错误处理和回退机制
### 3. 构建优化
- 图片资源统一放置在 `assets/images/` 目录
- 文件名包含hash值,支持缓存优化
- 构建后路径结构清晰
## 使用方式
### 在组件中使用图片
```vue
<template>
<!-- 方式1:直接使用 -->
<img :src="getStaticImage('components/person')" alt="人物" />
<!-- 方式2:作为背景图片 -->
<div :style="{ backgroundImage: getBackgroundImage('home/bg') }"></div>
<!-- 方式3:通过ImgButton组件 -->
<ImgButton :image="IMAGE_PATHS.BUTTONS.CONTINUE" />
</template>
<script setup>
import { getStaticImage, getBackgroundImage, IMAGE_PATHS } from '@/utils'
</script>
```
### 预定义图片路径常量
```typescript
export const IMAGE_PATHS = {
HOME_BG: 'home/guide/bg',
ACTION_BG: 'home/action/bg',
GUIDE_PERSON: 'components/person',
BUTTONS: {
CONTINUE: 'components/continue',
ESCAPE: 'components/escape'
}
} as const
```
## 验证结果
构建后验证:
- ✅ 所有图片资源正确包含在 `dist/assets/images/` 目录
- ✅ 图片路径在构建后正确解析
- ✅ 预览服务器中图片正常访问
- ✅ 支持hash文件名,便于缓存管理
## 注意事项
1. **不要将图片放在 `public` 目录**:这会导致图片不被编译和优化
2. **使用统一的图片管理函数**:避免直接使用相对路径
3. **确保图片文件存在**:构建时会检查所有引用的图片
4. **支持多种图片格式**:png, jpg, jpeg, gif, svg, webp
## 相关文件
- 图片处理工具:`src/utils/index.ts`
- Vite配置:`vite.config.ts`
- 组件示例:`src/components/Guide/GuideDragon.vue`
- 按钮组件:`src/components/Button/ImgButton.vue`
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

+2 -3
View File
@@ -8,7 +8,7 @@
<!-- 导学小龙UI区域 -->
<div class="guide-ui absolute left-16 top-1/2 transform -translate-y-1/2">
<!-- 主UI面板 -->
<div class="guide-panel">
<div class="guide-panel" :style="{ backgroundImage: getBackgroundImage('components/box') }">
<!-- 标题区域 -->
<ImgButton
@@ -60,7 +60,7 @@
</template>
<script setup lang="ts">
import { getStaticImage, IMAGE_PATHS } from '@/utils'
import { getStaticImage, getBackgroundImage, IMAGE_PATHS } from '@/utils'
import { ImgButton } from '@/components/Button'
interface Props {
@@ -119,7 +119,6 @@ const handleContinue = () => {
width: 1547px;
height: 279px;
padding: 75px 30px 30px 120px;
background-image: url('../../assets/images/components/box.png');
background-color: rgba(0, 0, 0, 0); /* 背景完全透明 */
}
+2 -2
View File
@@ -1,4 +1,4 @@
import { createRouter, createWebHistory } from 'vue-router'
import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
const routes: RouteRecordRaw[] = [
@@ -29,7 +29,7 @@ const routes: RouteRecordRaw[] = [
]
const router = createRouter({
history: createWebHistory(),
history: createWebHashHistory(),
routes
})
+13 -1
View File
@@ -1,4 +1,9 @@
//访问静态图片
// 图片资源映射 - 使用静态导入确保构建时包含所有图片
const imageModules = import.meta.glob('../assets/images/**/*.{png,jpg,jpeg,gif,svg,webp}', {
eager: true
})
//访问静态图片 - 使用静态导入确保构建后路径正确
export const getStaticImage = (path: string) => {
try {
// 确保路径以正确的格式结尾
@@ -12,6 +17,13 @@ export const getStaticImage = (path: string) => {
? `../assets/images/${path}`
: `../assets/images/${path}.png`
// 使用静态导入的模块
const module = imageModules[imagePath]
if (module && typeof module === 'object' && 'default' in module) {
return module.default as string
}
// 回退到URL方式
return new URL(imagePath, import.meta.url).href
} catch (error) {
console.error('Failed to load image:', path, error)
+3 -3
View File
@@ -63,18 +63,18 @@ onMounted(() => {
<div class="w-full h-full relative">
<!-- 背景图片 -->
<div
:class="['absolute inset-0 bg-cover bg-center bg-no-repeat', status ? 'z-0' : 'z-10']"
:class="['absolute inset-0 bg-cover bg-center bg-no-repeat']"
:style="{ backgroundImage: getBackgroundImage(IMAGE_PATHS.ACTION_BG) }"
></div>
<!-- 选择模块 -->
<div class="absolute left-0 top-[-140px] inset-0 z-10">
<div :class="['absolute left-0 top-[-140px] inset-0 z-[8]']">
<ModuleSwitcher v-model="selectedModule" @change="handleModuleChange" />
</div>
<!-- 电视机 -->
<div
class="absolute w-[765px] h-[768px] right-0 top-0 z-0 transition-opacity duration-200"
class="absolute w-[765px] h-[768px] right-0 top-0 z-[5] transition-opacity duration-200"
:class="{ 'opacity-50': isImageLoading }"
:style="{ backgroundImage: selectedImage }"
></div>
+1 -1
View File
@@ -21,7 +21,7 @@ import { ImgButton } from '@/components/Button'
</div>
<!-- 操作指引 -->
<div class="absolute right-0 bottom-0">
<ImgButton :image="IMAGE_PATHS.BUTTONS.OPERATE_GUIDE" :path="{ name: 'Guide' }" />
<ImgButton :image="IMAGE_PATHS.BUTTONS.OPERATE_GUIDE" />
</div>
</div>
</template>
+14 -1
View File
@@ -10,11 +10,24 @@ export default defineConfig(({ mode }) => {
const env = loadEnv(mode, root, '')
return {
plugins: [vue()],
base: env.VITE_BASE_PATH || '/',
base: env.VITE_NODE_ENV === 'development' ? '/' : './',
resolve: {
alias: {
'@': resolve(__dirname, 'src')
}
},
build: {
assetsDir: 'assets',
rollupOptions: {
output: {
assetFileNames: assetInfo => {
if (/\.(png|jpe?g|gif|svg|webp)$/i.test(assetInfo.name || '')) {
return `assets/images/[name]-[hash][extname]`
}
return `assets/[name]-[hash][extname]`
}
}
}
}
}
})