electron 打包后 运行正确加载css字体方式
- 在 electron 的 main.js 里面添加以下代码:
const { app, BrowserWindow } = require('electron');
const path = require('path');
function createWindow() {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
mainWindow.loadFile('index.html');
}
app.on('ready', () => {
createWindow();
// 在页面加载完成后再加载字体文件
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.webContents.insertCSS(`
@font-face {
font-family: 'My Font';
src: url('${path.join(__dirname, 'fonts/MyFont.ttf')}');
}
`);
});
});
- 在你的样式文件里面使用字体:
body {
font-family: 'My Font', sans-serif;
}
-
将字体文件放到你的项目里面的某个地方,比如
fonts/MyFont.ttf。 -
执行
npm run build命令打包你的 electron 应用。 -
运行打包后的应用,确保字体正常加载
原文地址: https://www.cveoy.top/t/topic/eEVp 著作权归作者所有。请勿转载和采集!