在JavaScript中,完全禁止查看源码是不可能的,因为浏览器需要执行这些代码,就必须能够访问和解析它们。不过,可以采取一些措施来增加查看源码的难度,或者使源码变得难以理解。
// 安装Terser
// npm install terser -g
// 原始代码(example.js)
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("World");
// 混淆代码
terser example.js -o example.min.js -c -m
混淆后的example.min.js
可能看起来像这样:
function greet(n){console.log("Hello, "+n+"!")}greet("World");
// main.js
fetch('obfuscated-script.js')
.then(response => response.text())
.then(script => {
eval(script); // 注意:使用eval有安全风险,应谨慎使用
});
// obfuscated-script.js 是经过混淆的JavaScript代码
虽然无法完全禁止查看源码,但通过代码混淆、压缩和动态加载等技术,可以显著增加查看和理解的难度,从而在一定程度上保护你的代码。