
在 Vue 3 + Vite 项目中,如果你想在 build 阶段对代码进行加密或混淆,通常是为了防止源码被轻易反编译和阅读。
不过需要注意:
1. 使用 Vite 插件混淆(常用做法)
可以用 JavaScript Obfuscator 结合 Vite 插件进行构建时混淆:
安装依赖
pnpm add -D vite-plugin-obfuscator javascript-obfuscator
配置 vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import obfuscatorPlugin from 'vite-plugin-obfuscator'
export default defineConfig({
plugins: [
vue(),
obfuscatorPlugin({
// 匹配需要混淆的文件
include: [/\.js$/],
options: {
compact: true, // 压缩代码
controlFlowFlattening: true, // 控制流扁平化
controlFlowFlatteningThreshold: 0.75,
numbersToExpressions: true,
simplify: true,
stringArray: true,
stringArrayEncoding: ['base64'], // 字符串加密
stringArrayThreshold: 0.75,
rotateStringArray: true
}
})
]
})
这样 vite build
之后生成的 dist
内 .js
文件会被混淆处理。
2. 对敏感逻辑加密(可配合混淆)
如果你不想全量混淆,而是只加密关键算法,可以在打包前:
示例:
import CryptoJS from 'crypto-js'
const encrypted = 'U2FsdGVkX1+0bB...'
// 运行时解密
const decrypted = CryptoJS.AES.decrypt(encrypted, 'your-secret-key').toString(CryptoJS.enc.Utf8)
new Function(decrypted)()
这种方式比纯混淆安全性稍高,但运行性能会差一些。
3. 额外建议
-
如果你只是想防止源码被随意阅读,混淆 + 压缩足够了
-
如果需要更高安全性,可以将核心逻辑放到 WebAssembly(WASM)中,然后在 Vue 里调用
-
生产环境记得关闭 sourcemap
,否则混淆没意义:
build: {
sourcemap: false
}
如果你愿意,我可以帮你直接写一个 Vue3 + Vite 项目完整可运行的混淆构建配置,这样你直接 vite build
就能得到加密混淆后的代码。
这样你就不需要自己再拼插件配置了。