VueJS Vite中如何单独为资源设置/vue/基础路径且不改变路由URL
问题描述
我有一个VueJS + Vite项目,需要构建到现有项目根目录下的/vue/目录中,项目文件夹结构如下:
project │ Controllers │ ... │ └───Vue <!-- Base App --> │ │ vite.config.ts │ │ │ └───src │ │ App.vue │ │ │ └───assets │ │ image-test.webp │ │ ... │ └───wwwroot │ └───css │ └───img │ └───vue <!-- Build Directory --> │ │ index.html │ │ │ └───assets │ │ image-test.webp │ │ ...
当前问题:除资源外其他部分运行正常,比如如下组件:
<script setup lang="ts"> import imageSource from '@/assets/image-test.webp'; </script> <template> <img :src="imageSource" /> </template>
构建后图片无法显示,原因是默认基础URL为/,但应用实际部署在/vue/路径下。手动将图片URL改为/vue/assets/image-test.webp后可正常显示。
尝试过在vite.config.ts中设置base: '/vue',资源加载正常了,但所有路由URL都会自动加上/vue/前缀(比如原/Controller/Method/Param会变成/vue/Controller/Method/Param),不符合需求。
需要实现:资源使用/vue/作为基础路径,而路由等其他部分保持使用/作为基础路径。
解决方案
方法1:自定义资源路径前缀,不修改全局base
在vite.config.ts中,通过Rollup输出配置指定资源的路径前缀,全局base保持根路径:
// vite.config.ts import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { resolve } from 'path' export default defineConfig({ plugins: [vue()], // 全局base保持根路径,不影响路由 base: '/', resolve: { alias: { '@': resolve(__dirname, 'src') } }, build: { // 指定构建输出到目标目录 outDir: '../wwwroot/vue', rollupOptions: { output: { // 给所有资源文件添加/vue/前缀 assetFileNames: 'vue/assets/[name]-[hash][extname]', chunkFileNames: 'vue/assets/[name]-[hash].js', entryFileNames: 'vue/assets/[name]-[hash].js' } } } })
配置后,构建出的资源路径自动带上/vue/assets/前缀,路由基础路径依然为/,不会被修改。
方法2:组件内手动处理资源路径(适合少量资源场景)
如果不想修改Vite配置,可在组件中手动给资源路径添加前缀:
<script setup lang="ts"> import imageSource from '@/assets/image-test.webp'; // 手动拼接/vue/前缀 const formattedImageSource = `/vue${imageSource}`; </script> <template> <img :src="formattedImageSource" /> </template>
这种方式适合资源数量不多的场景,操作简单直接。
方法3:用Vite钩子修改index.html中的资源路径
通过Vite的transformIndexHtml钩子,在构建时自动替换index.html里的资源引用路径:
// vite.config.ts import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [ vue(), { name: 'modify-asset-path', transformIndexHtml(html) { // 替换所有assets开头的资源路径为/vue/assets/ return html.replace(/src="assets\//g, 'src="/vue/assets/') .replace(/href="assets\//g, 'href="/vue/assets/') } } ], base: '/', build: { outDir: '../wwwroot/vue' } })
该方法会在构建阶段自动修正资源引用,同时不影响路由的基础路径。
内容的提问来源于stack exchange,提问作者Sgt_Scott
相关产品推荐
相关产品推荐

