Laravel10+Vue3项目npm run build报错:无法解析/icons/coreui.svg路径
Laravel 10/Vue3 项目
npm run build 图标资源解析错误解决方法 问题描述
开发环境执行 npm run dev 时资源编译正常,图标显示正常,但执行 npm run build 时出现 Rollup 解析错误:
[vite]: Rollup failed to resolve import "/icons/coreui.svg" from "C:/xampp/htdocs/project/resources/js/layouts/Product/Update.vue". This is most likely unintended because it can break your application at runtime. If you do want to externalize this module explicitly add it to `build.rollupOptions.external` error during build: Error: [vite]: Rollup failed to resolve import "/icons/coreui.svg" from "C:/xampp/htdocs/project/resources/js/layouts/Product/Create.vue". This is most likely unintended because it can break your application at runtime. If you do want to externalize this module explicitly add it to `build.rollupOptions.external`
图标使用代码:
<svg class="me-1 mb-1" width="20" height="20"> <use xlink:href="/icons/coreui.svg#cil-save"></use> </svg>
图标位于项目 public/icons/coreui.svg 路径。
问题原因
开发环境下,Vite 开发服务器会自动代理 public 目录的静态资源,直接使用绝对路径 /icons/coreui.svg 可正常访问;但生产构建时,Rollup 会将所有路径视为模块导入尝试解析,而 public 目录下的资源不属于项目源码或依赖模块,因此抛出解析错误。
解决方案
方案1:配置 Rollup 忽略静态资源路径
修改 vite.config.js,添加 build.rollupOptions.external,告诉 Rollup 不要解析指定的静态资源路径:
import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; import vue from '@vitejs/plugin-vue'; import path from 'path'; export default defineConfig({ plugins: [ vue(), laravel({ input: [ 'resources/sass/app.scss', 'resources/sass/style.scss', 'resources/js/app.js', ], refresh: true, }), ], resolve: { alias: { '~bootstrap': path.resolve(__dirname, 'node_modules/bootstrap'), } }, build: { rollupOptions: { // 用正则匹配所有 /icons 下的 svg 文件,避免逐个添加 external: [/^\/icons\/.*\.svg$/], } }, });
方案2:使用 Vite URL 方式生成路径
修改 Vue 组件中的图标引用代码,通过 new URL() 生成正确路径,避免 Rollup 将其视为模块导入:
<svg class="me-1 mb-1" width="20" height="20"> <use :xlink:href="`${new URL('/icons/coreui.svg', import.meta.url)}#cil-save`"></use> </svg>
方案3:配置别名指向 public 目录的图标
修改 vite.config.js 的 resolve.alias,让 Rollup 能找到 public/icons 目录下的文件:
import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; import vue from '@vitejs/plugin-vue'; import path from 'path'; export default defineConfig({ plugins: [ vue(), laravel({ input: [ 'resources/sass/app.scss', 'resources/sass/style.scss', 'resources/js/app.js', ], refresh: true, }), ], resolve: { alias: { '~bootstrap': path.resolve(__dirname, 'node_modules/bootstrap'), '/icons': path.resolve(__dirname, 'public/icons'), } }, });
内容的提问来源于stack exchange,提问作者karl
相关产品推荐
相关产品推荐

