Vite使用inline导入CSS Module时剥离@font-face的解决方案问询
解决Vite inline导入CSS时保留@font-face的方案
针对你在库开发中遇到的Vite使用?inline导入CSS Modules时丢失@font-face规则的问题,有几个可行的解决思路:
方案一:拆分样式文件,分别导入后合并
把@font-face规则单独放在一个独立的CSS文件(比如fonts.css),用?raw后缀导入获取原始CSS字符串,再和组件的inline样式合并:
/* fonts.css */ @font-face { font-family: 'ClockFace'; src: url('./assets/fonts/VictorMono-Regular.woff2') format('woff2'), url('./assets/fonts/VictorMono-Regular.woff') format('woff'), url('./assets/fonts/VictorMono-Regular.ttf') format('ttf'); }
// 组件文件中 import componentStyles from './Component.module.css?inline'; import fontStyles from './fonts.css?raw'; // 合并样式后自行处理注入 const fullStyles = fontStyles + componentStyles; // 示例:创建style标签注入到DOM const styleEl = document.createElement('style'); styleEl.textContent = fullStyles; document.head.appendChild(styleEl);
这种方式下,fonts.css的内容不会被Vite修改,@font-face规则完整保留,同时组件样式的?inline仍能正常处理资源转Base64。
方案二:配置Vite库打包自动内联样式
如果你的核心需求是避免用户手动导入style.css,可以直接调整Vite的库打包配置,让样式自动内联到JS产物中,无需使用?inline:
在vite.config.js中设置:
import { defineConfig } from 'vite'; export default defineConfig({ build: { lib: { entry: './src/index.js', // 你的库入口文件 name: 'YourLibraryName', fileName: 'your-library' }, cssCodeSplit: false, // 禁用CSS代码拆分,将所有样式打包进JS rollupOptions: { // 根据你的需求配置外部依赖,比如Vue/React等 external: ['vue'], output: { globals: { vue: 'Vue' } } } } });
然后在库的入口文件中直接导入组件的CSS Modules:
// src/index.js import './Component.module.css'; export { default as YourComponent } from './YourComponent.vue';
打包后的JS文件会自动包含样式内容(包括@font-face),用户只需要导入组件即可,无需额外处理样式文件。
方案三:自定义PostCSS插件保留@font-face
如果一定要用?inline且不想拆分文件,可以通过自定义PostCSS插件阻止Vite移除@font-face规则:
在vite.config.js中添加PostCSS插件:
import { defineConfig } from 'vite'; export default defineConfig({ css: { postcss: { plugins: [ { postcssPlugin: 'preserve-font-face', AtRule: { 'font-face': (rule) => { // 标记该规则不被后续处理移除 rule.raws.preserve = true; } } } ] } } });
这个插件会在PostCSS处理阶段标记@font-face规则为保留状态,避免被Vite的inline逻辑剥离。
内容的提问来源于stack exchange,提问作者oravecz
相关产品推荐
相关产品推荐

