Vue3/Vite构建npm包时,如何实现字体路径动态适配?
解决Vue3/Vite构建npm包时字体路径适配问题
问题根源
构建npm包时,SCSS中用绝对路径/assets/能让Vite正常解析,但其他应用引用该包时,会错误地去自身项目的public/assets找字体文件;改用相对路径./assets/则会导致包构建阶段Vite无法定位资源。核心需求是让路径根据构建场景动态切换:包构建时适配Vite解析逻辑,应用引用时指向包内dist/assets目录。
解决方案一:用环境变量动态注入SCSS路径变量
- 安装cross-env(跨平台设置环境变量)
npm install cross-env --save-dev
- 修改package.json构建命令,标记构建场景
{ "scripts": { "build": "cross-env BUILD_LIB=true vite build", "dev": "vite", "storybook": "storybook dev -p 6006" } }
- 更新vite.config.js,动态设置资源路径
import { fileURLToPath, URL } from 'node:url' import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' const path = require("path") export default defineConfig(({ mode }) => { const isBuildLib = process.env.BUILD_LIB === 'true' // 构建包时用相对路径,开发/Storybook时用绝对路径 const assetPath = isBuildLib ? './assets/' : '/assets/' return { plugins: [vue()], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)), 'assets': fileURLToPath(new URL('./assets', import.meta.url)), } }, css: { preprocessorOptions: { scss: { additionalData: `@import "@/styles/__main.scss"; $r-asset-path: '${assetPath}';` }, }, }, build: { lib: { entry: path.resolve(__dirname, "src/main.ts"), name: "ui-vue3", fileName: (format) => `ui-vue3.${format}.js`, }, rollupOptions: { external: ["vue"], output: { globals: { vue: "Vue", }, // 固定资源输出目录 assetFileNames: 'assets/[name].[hash][extname]' }, }, assetsInlineLimit: 0 } } })
- 调整SCSS字体引用,使用动态变量
@font-face { font-family: 'CustomFont'; src: url($r-asset-path + 'fonts/custom-font.woff2') format('woff2'); }
解决方案二:将字体移至src/assets目录(更推荐)
把字体文件从public移到src/assets/fonts,让Vite直接处理资源:
- 修改SCSS路径,用别名引用
@font-face { font-family: 'CustomFont'; src: url('~@/assets/fonts/custom-font.woff2') format('woff2'); }
- 配置rollup资源输出
在build.rollupOptions.output中添加:
assetFileNames: 'assets/[name].[hash][extname]'
Vite会自动将字体打包到dist/assets,生成的CSS会包含正确的相对路径,其他应用引用时会自动指向包内资源目录。
验证步骤
- 执行
npm run build,检查dist/assets是否包含字体文件 - 在测试项目中安装包并引用组件,确认字体请求路径指向
node_modules/your-package/dist/assets/xxx
内容的提问来源于stack exchange,提问作者Gabriella Tavares
相关产品推荐
相关产品推荐

