Electron+React项目中JetBrains Mono字体加载异常求助
问题描述
在基于React的Electron项目中,我通过链接https://fonts.googleapis.com/css?family=JetBrains Mono引入JetBrains Mono字体,但Electron应用无法正确显示该字体;通过localhost在浏览器运行时,字体效果接近正确但仍有偏差。附浏览器、Figma、Electron应用的字体效果对比图。我尝试关闭Electron的Web安全功能,但问题未解决,刚接触Electron还没尝试其他方案。
相关代码如下:
index.css 文件代码
body { display: flex; flex-direction: column; font-family: 'JetBrains Mono', monospace; color: #A5D7E8; background-color: #0B2447; }
index.html 的head标签代码
<head> <meta charset="UTF-8" /> <title>Electron</title> <link href='https://fonts.googleapis.com/css?family=JetBrains Mono' rel='stylesheet'> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'" /> </head>
解决方案
1. 调整内容安全策略(CSP)
当前CSP限制样式资源仅能从self加载,导致Google字体的外部样式文件被拦截。修改CSP,允许从Google字体域名加载资源:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com" />
2. 修正字体链接格式
字体名称含空格时,Google字体URL需用+替代空格,否则可能解析失败。更新链接为:
<link href='https://fonts.googleapis.com/css?family=JetBrains+Mono' rel='stylesheet'>
也可使用v2版本的链接,支持更多字体参数:
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono&display=swap" rel="stylesheet">
3. 本地引入字体(稳定方案)
若外部加载仍有问题,直接下载JetBrains Mono字体文件(TTF/OTF),放到项目public/fonts目录,通过@font-face本地引入:
@font-face { font-family: 'JetBrains Mono'; src: url('./fonts/JetBrainsMono-Regular.ttf') format('truetype'); font-weight: normal; font-style: normal; } body { display: flex; flex-direction: column; font-family: 'JetBrains Mono', monospace; color: #A5D7E8; background-color: #0B2447; }
本地引入完全规避网络和CSP限制,字体显示更一致。
4. 检查Electron窗口配置
确保主进程的窗口webPreferences未禁用必要设置,修复CSP后建议开启webSecurity保障安全:
const mainWindow = new BrowserWindow({ webPreferences: { nodeIntegration: false, contextIsolation: true, webSecurity: true // 修复CSP后无需关闭 } });
内容的提问来源于stack exchange,提问作者Freeeeky
相关产品推荐
相关产品推荐

