terserJS混肴
混肴的作用
防止浏览器的js/html/css代码被他人盗用。下述只实现了js的混肴。html/css可仿照js逻辑实现
预览图
mix.sh混肴脚本
#!/bin/bash
# 检查 terser 是否可用
if ! command -v terser &> /dev/null; then
echo "terser 不可用,请安装 terser 后再运行此脚本。执行安装: npm install -g terser"
exit 1
fi
# 获取当前目录下的所有子目录(只考虑一级子目录)并自然排序
dirs=($(find . -maxdepth 1 -mindepth 1 -type d -exec basename {} \; | sort))
# 显示目录列表并让用户选择
for (( i=0; i<${#dirs[@]}; i++ )); do
echo "$((i + 1)). ${dirs[$i]}"
done
read -p "请选择js存储目录(1-${#dirs[@]}):" choice1
# 检查输入是否有效
if ! [[ "$choice1" =~ ^[1-9][0-9]*$ ]] || [[ "$choice1" -gt ${#dirs[@]} ]]; then
echo "无效的输入,请重新运行脚本"
exit 1
fi
# 转换为0-based索引
choice1=$((choice1-1))
selected_dir="./${dirs[$choice1]}"
# 第二步:列出目录下的js文件并自然排序
files=($(find "$selected_dir/js" -type f -name "*.js" | sort))
# 显示文件列表并让用户选择
for (( i=0; i<${#files[@]}; i++ )); do
filename=$(basename -- "${files[$i]}")
echo "$(($i+1))). ${filename}"
done
read -p "请选择要混肴的js(1-${#files[@]})" choice2
# 检查输入是否有效
if ! [[ "$choice2" =~ ^[1-9][0-9]*$ ]] || [[ "$choice2" -gt ${#files[@]} ]]; then
echo "无效的输入,请重新运行脚本"
exit 1
fi
# 转换为0-based索引
choice2=$((choice2-1))
full_file_path="${files[$choice2]}"
echo "混肴的js路径:$full_file_path"
# 第三步:执行混淆并保存到新位置
dir_part="${full_file_path%/*}" # 移除最后一个 / 及其后的内容
dir_part="${dir_part#./}" # 如果需要,移除开头的 ./
output_dir="./copy/$dir_part"
mkdir -p "$output_dir" # 确保目录存在
output_file="./copy/${full_file_path#./}" #去掉./前缀
# https://github.com/terser/terser
#--mangle-props 保留属性名称
# drop_console=true 去掉console.log
##--mangle:启用变量名和函数名的混淆。默认情况下,Terser 会尝试混淆所有可以混淆的标识符,包括变量名和函数名。
#terser "$full_file_path" -o "$output_file" -c drop_console=true --mangle-props
# terser "$full_file_path" -o "$output_file" -config-file config.json
terser "$full_file_path" -o "$output_file" -c --mangle
echo "混淆后的文件已保存到:$output_file"
#目录结构必须是/主目录/js/*.js
config.json
{
"parse": {},
"compress": {
"drop_console": true,
"drop_debugger": true
},
"mangle": {
"properties": true,
"toplevel": false
},
"format": {},
"sourceMap": {},
"keep_classnames": true,
"keep_fnames": true,
"ie8": false,
"module": false,
"nameCache": null,
"safari10": false
}