目录
[javascript-obfuscator
]是一款功能强大的 JavaScript 混淆工具,可将源代码转换为难以阅读和还原的形式,广泛用于前端源码保护和反爬虫处理。
✅ 一、安装方法
使用 npm 全局安装(推荐):
npm install -g javascript-obfuscator
安装成功后,可通过终端命令 javascript-obfuscator
直接调用。
🛠️ 二、基本用法
原始文件 hello.js
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("World");
执行混淆:
javascript-obfuscator hello.js --output hello.obf.js
会生成混淆后的文件 hello.obf.js
,代码将被加密、变量名重命名,逻辑结构扁平化。
⚙️ 三、常用命令行参数说明
参数 | 类型 | 默认值 | 说明 |
---|---|---|---|
--compact | boolean | true | 是否压缩代码,去除空格和换行 |
--controlFlowFlattening | boolean | false | 控制流扁平化,重构为状态机逻辑,显著提升混淆难度,但影响性能 |
--controlFlowFlatteningThreshold | number (0~1) | 0.75 | 控制多少比例的代码节点被扁平化 |
--stringArray | boolean | true | 是否将字符串提取为数组项 |
--stringArrayEncoding | "base64" / "rc4" / false | false | 对字符串数组进行编码,防止直接读取 |
--splitStrings | boolean | false | 拆分长字符串为若干片段 |
--splitStringsChunkLength | number | 10 | 拆分后的最小字符串长度 |
--selfDefending | boolean | false | 添加防调试与反格式化保护 |
--transformObjectKeys | boolean | false | 混淆对象属性名 |
--deadCodeInjection | boolean | false | 插入无用代码增加逆向难度 |
--identifierNamesGenerator | "hexadecimal" / "mangled" / "dictionary" | "hexadecimal" | 变量和函数名混淆风格 - hexadecimal :生成形如 _0xabc123 的名字(默认)- mangled :生成短小的如 a , b , c 名称- dictionary :使用自定义字典(配合 identifierNamesGeneratorDictionary ) |
⚠️ 性能提示:controlFlowFlattening
- 此选项会显著增加代码体积,最多导致 1.5 倍的运行时间下降;
- 通常建议只对关键逻辑开启,如登录认证、接口校验等;
- 可通过
controlFlowFlatteningThreshold
控制混淆强度。
📄 四、使用配置文件(推荐)
将参数写入 JSON 文件更易管理:
obfuscator-config.json
{
"compact": true,
"controlFlowFlattening": true,
"controlFlowFlatteningThreshold": 0.8,
"stringArray": true,
"stringArrayEncoding": ["base64"],
"stringArrayThreshold": 1,
"splitStrings": true,
"splitStringsChunkLength": 3,
"selfDefending": true,
"transformObjectKeys": true
}
使用命令:
javascript-obfuscator hello.js --output hello.obf.js --config obfuscator-config.json
📁 五、批量混淆目录
将整个目录中的 JS 文件进行混淆处理:
javascript-obfuscator ./src --output ./dist --config obfuscator-config.json
src/
:原始源代码目录dist/
:混淆后输出目录- 目录结构会自动保留。
💡 六、实用示例合集
1️⃣ 简单压缩
javascript-obfuscator main.js --output main.min.js --compact true
2️⃣ 最大强度混淆(慎用)
javascript-obfuscator secret.js --output secret.secure.js \
--controlFlowFlattening true \
--controlFlowFlatteningThreshold 1 \
--stringArray true \
--stringArrayEncoding base64 \
--splitStrings true \
--selfDefending true \
--deadCodeInjection true
🔍 七、常见问题与建议
❓运行变慢?
- 检查是否启用了
controlFlowFlattening
、splitStrings
等高混淆度选项; - 可关闭部分选项进行对比测试。
❓打包后报错?
- 某些脚本工具或压缩器(如 UglifyJS)可能无法兼容
selfDefending
; - 不要同时使用多个压缩/混淆器。
❓是否推荐前端项目全面混淆?
- 建议只混淆敏感逻辑、关键算法模块;
- 常规 UI 展示代码无需混淆,利于调试和维护。
🧩 八、总结与最佳实践
场景 | 建议配置 |
---|---|
开发调试 | 不混淆或仅压缩 --compact true |
普通项目上线 | 使用字符串混淆与压缩 |
有登录校验、反爬逻辑 | 加上 controlFlowFlattening 、stringArrayEncoding |
高保密需求(但可牺牲性能) | 所有混淆选项全开,阈值调高 |
📌 官网与资源
- 🌐 在线体验版:https://obfuscator.io
- 🧾 GitHub 项目地址:https://github.com/javascript-obfuscator/javascript-obfuscator
- 📚 官方配置说明:配置文档(Options)