electron 包大小优化
减少包的体积
1. 删掉 electron Locales 目录下的用不到的语言
electron builder 打包完成后 根目录有一个 locales 语言包
这个包很大,解压后 33MB - 优化后可以到 1.53MB
根据你软件所需要的语言即可,一般我们只要英文和中文
参考
- electron 官网 http://man.hubwiz.com/docset/electron.docset/Contents/Resources/Documents/docs/api/locales.html
- github issues https://github.com/electron/electron/issues/18738#issuecomment-511704668
- electron builder https://www.electron.build/configuration/configuration#afterpack
具体代码如下:
- 项目根目录创建一个 removeLocales.js 文件, 内容如下
js
// removeLocales.js
/**
* 移除部分用不到的语言、优化electron包的大小
*/
exports.default = async function (context) {
const fs = require("fs");
const localeDir = context.appOutDir + "/locales/";
fs.readdir(localeDir, function (err, files) {
//files is array of filenames (basename form)
if (!(files && files.length)) return;
for (let i = 0, len = files.length; i < len; i++) {
// zh 和 en 开头的都不删
if (!(files[i].startsWith("en") || files[i].startsWith("zh"))) {
fs.unlinkSync(localeDir + files[i]);
}
}
});
};
- package.json build electron builder 配置如下
json
{
"build": {
"afterPack": "./removeLocales.js",
"artifactName": "videovlc-${os}-${arch}-${version}.${ext}",
"win": {
"target": "nsis"
},
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": true,
"deleteAppDataOnUninstall": true
},
"extraResources": [
{
"from": "./vlc-3.0.9.2",
"to": "vlc-3.0.9.2",
"filter": [
"**/*",
"!locale/**",
"!skins/**",
"!lua/**",
"!msi/**",
"!**/*.txt",
"!**/*.TXT",
"!**/*.html",
"!**/*.md",
"!*.exe",
"!**/*.ico",
"!languages/**"
]
},
{
"from": "./bin",
"to": "bin"
}
],
"files": [
"**/*",
"!bin/**/*",
"!build/**/*",
"!vlc-3.0.9.2/**/*",
"!path_to_some_media_file.mp4"
]
},
"devDependencies": {
"electron": "^26.2.4",
"electron-builder": "^24.6.4"
}
}