如何在Electron React Boilerplate中集成本地字体(无需系统安装)
解决Electron React项目自定义本地字体无需系统安装的问题
核心问题分析
当前配置的@font-face存在路径指向错误、格式值不标准的问题,同时Webpack未正确处理字体资源的打包流程,导致只有系统安装字体时才能生效。
解决方案步骤
1. 修正@font-face配置
- 调整路径为相对当前SCSS文件的正确路径,或使用Webpack别名简化路径管理
- 将
format('ttf')改为标准的format('truetype')
方式一:使用相对路径
假设项目结构为:
项目根目录 ├── assets/fonts/Bariol-Regular.ttf └── src/renderer/scss/commons/_fonts.scss
修改_fonts.scss中的配置:
@font-face { font-family: 'Bariol Regular'; font-style: normal; font-weight: normal; src: local('Bariol Regular'), url('../../../../assets/fonts/Bariol-Regular.ttf') format('truetype'); }
方式二:使用Webpack别名(推荐)
在renderer的Webpack配置中添加别名:
const path = require('path'); module.exports = { // ...其他配置 resolve: { alias: { '@assets': path.resolve(__dirname, '../../assets') // 指向根目录下的assets文件夹 } } };
然后在SCSS中使用别名(注意前缀~):
@font-face { font-family: 'Bariol Regular'; font-style: normal; font-weight: normal; src: local('Bariol Regular'), url('~@assets/fonts/Bariol-Regular.ttf') format('truetype'); }
2. 配置Webpack打包字体资源
确保Webpack能正确识别并打包字体文件,添加对应loader配置:
module.exports = { // ...其他配置 module: { rules: [ // ...其他loader规则 { test: /\.(woff|woff2|eot|ttf|otf)$/i, type: 'asset/resource', generator: { filename: 'assets/fonts/[name][ext]' // 指定打包后字体文件的输出位置 } } ] } };
3. 调整Webpack的publicPath设置
保证开发和生产环境下资源路径都能正确访问:
module.exports = { // ...其他配置 output: { // ...其他输出配置 publicPath: process.env.NODE_ENV === 'development' ? 'http://localhost:3000/' : './' } };
4. 验证字体应用
在CSS中使用字体时,确保font-family名称与@font-face中定义的完全一致:
// 示例:全局应用字体 body { font-family: 'Bariol Regular', sans-serif; }
内容的提问来源于stack exchange,提问作者Davide Taurisano
相关产品推荐
相关产品推荐

