前言

首先感谢 JavaScript Obfuscator Tool 提供的这个工具。

直接上代码

这里我们写个 vite 插件,直接调用即可

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import JavaScriptObfuscator from "javascript-obfuscator";
import { minify } from "terser";

export function codeObfuscator(): any {
  return [
    {
      name: "code-obfuscator",
      enforce: "post",
      async transform(code) {
        //  先压缩然后再进行混淆
        //  因为 import.meta.env 可能会出现引用对象的问题
        //  比如 {a:'foo',b:'bar'}.a
        //  压缩后 'foo'
        const res = await minify(code);
        const content = res.code || code;

        //  在下面配置你的参数
        let obfuscationResult = JavaScriptObfuscator.obfuscate(content, {
          compact: true,
          controlFlowFlattening: true,
          controlFlowFlatteningThreshold: 1,
          numbersToExpressions: true,
          simplify: true,

          stringArray: true,
          stringArrayCallsTransform: true,
          stringArrayEncoding: ["base64", "rc4"],
          stringArrayIndexShift: true,
          stringArrayRotate: true,
          stringArrayShuffle: true,
          stringArrayWrappersCount: 3,
          stringArrayWrappersChainedCalls: true,
          stringArrayWrappersParametersMaxCount: 2,
          stringArrayWrappersType: "variable",
          stringArrayThreshold: 1,

          splitStrings: true,
          unicodeEscapeSequence: true,
        });

        return obfuscationResult.getObfuscatedCode();
      },
    },
  ];
}