node-font-list
node-font-list copied to clipboard
electron使用font-list的正确方法,支持windows和mac
正常情况下,electron-builder
默认是不会将 font-list
打包的,所以导致无法使用,通过 extraResources
执行处理即可,下面为使用步骤:
- 在
package.json
中添加
"extraResources": [
"./extraResources/**"
],
- 在项目根目录创建
extraResources/fontlist
文件夹,将node_modules/font-list
下的文件源码复制到extraResources
下
extraResources
└─fontlist
├─getSystemFonts.js
├─index.d.ts
├─index.js
└─libs
├─darwin
├─linux
└─win32
-
getSystemFonts.js
中为
const { getFonts } = require('./index');
function getSystemFonts() {
return new Promise((resolve, reject) => {
getFonts({ disableQuoting: true })
.then((fonts) => {
fonts = [...new Set(fonts)];
resolve(fonts || []);
})
.catch((err) => {
resolve([]);
});
});
}
(async () => {
const fonts = await getSystemFonts();
// process 处理
process.send(fonts);
// console.log('fonts', fonts);
})();
- 在主进程
main.ts
中添加触发事件getSystemFonts
import path from 'path';
import cp from 'child_process';
const EXTRARESOURCES_PATH = app.isPackaged
? path.join(process.resourcesPath, 'extraResources')
: path.join(__dirname, '../../extraResources');
const getExtraResourcesPath = (...paths: string[]): string => {
return path.join(EXTRARESOURCES_PATH, ...paths);
};
// ...
ipcMain.on('getSystemFonts', async () => {
const systemFontsScriptPath = getExtraResourcesPath('fontlist/getSystemFonts.js')
let fonts: string[] = [];
const forked = cp.fork(systemFontsScriptPath);
forked.on('message', function (message: string[]) {
fonts = message;
mainWindow?.webContents.send('getSystemFontsCb', fonts);
});
});
- 以
utils/common.ts
为例子触发事件
import { ipcRenderer } from "electron";
export const systemFonts: string[] = [];
// 获取系统字体列表
ipcRenderer.send('getSystemFonts');
ipcRenderer.on('getSystemFontsCb', (e, fonts: string[] = []) => {
// console.log('fonts', fonts);
systemFonts = fonts;
});
- 引用即可
import { systemFonts } from "utils/common";
console.log('systemFonts', systemFonts)
// [ 'Arial', 'Bahnschrift', 'Book Antiqua']
具体commit源码 https://github.com/Beats0/bilive-danmaku/commit/0f3f45004bc1964a6bbb85de7993dbf49524f721
嗯,我也是手动拷贝了一份,放到一个文件夹里。但是,这只是个workaround
extraResources: [
'bin/*',
],