找到了解决方案,在此记录,如果有遇到相同问题的朋友可以借鉴:
*packager.json*
...
"build": {
...
"afterSign": "./build_resource/afterSign.js",
...
}
...
*/packager.json*
*afterSign.js*
const fs = require('fs')
const path = require('path');
const asar = require('asar');
const JavaScriptObfuscator = require('javascript-obfuscator'); //使用 javascript-obfuscator 代码混淆
//获取指定文件夹下排除指定类型的文件
function getFiles(dirpath, exclude){
function getFiles_(dir, arr){
const stat = fs.statSync(dir);
if(stat.isDirectory()){
const dirs = fs.readdirSync(dir);
dirs.forEach(value => {
let extname = path.extname(value);
if(exclude.includes(extname)) arr.push(path.join(dir,value));
if(extname == "" && exclude.includes(value)) getFiles_(path.join(dir,value), arr);
})
}
else if(stat.isFile()){
//文件
if(exclude.includes(dir)) arr.push(dir);
}
};
let arrs = [];
getFiles_(dirpath, arrs);
return arrs;
}
exports.default = async ({appOutDir, packager}) => {
try{
const asarPath = path.join(packager.getResourcesDir(appOutDir), 'app.asar');
let appPath = path.join(packager.getResourcesDir(appOutDir), 'app');
if(fs.existsSync(asarPath)){
//如果存在 asar 压缩包
asar.extractAll(asarPath, appPath);
}
// 替换文件内容
let fileArrs = getFiles(appPath, ["app", "assets", "js", ".js"]);
console.log("等待加密文件:", fileArrs)
for(let i = 0;i < fileArrs.length;i++){
let con = fs.readFileSync(fileArrs[i],'utf8');
console.log("当前加密文件:", fileArrs[i])
let obfuscationResult = JavaScriptObfuscator.obfuscate(con, {
compact: true,
debugProtection: true,
disableConsoleOutput: true,
numbersToExpressions: true,
simplify: true,
stringArrayShuffle: true,
splitStrings: true,
stringArrayThreshold: 1
});
fs.writeFileSync(fileArrs[i], obfuscationResult.getObfuscatedCode());
}
// console.log('asar content replacement completed.');
// if(fs.existsSync(asarPath)){
// fs.unlinkSync(asarPath);
// console.log('delete the original asar.');
// }
// await asar.createPackage(appPath, asarPath);
// fs.rmdirSync(appPath,{recursive:true});
// console.log('create new asar.');
}catch(err){
console.error(err);
}
}
*/afterSign.js*