赞
踩
- "vue": "2.6.12",
- "@vue/cli-service": "4.4.6",
- "javascript-obfuscator": "^4.1.1",
- "terser-webpack-plugin": "^4.2.3",
- "vue-template-compiler": "2.6.12",
- "webpack-obfuscator": "^2.6.0"
为了对公司项目进行安全防护措施,前端需要进行代码混淆加密处理。
这里就有个三个需求点:
以此在网上查找到相应工具有:Terser、WebpackObfuscator
Terser:压缩代码、变量和函数名混淆、删除未使用代码
WebpackObfuscator:代码混淆、字符串加密、控制流扁平化
- npm install --save-dev terser-webpack-plugin@4
- npm install --save-dev javascript-obfuscator webpack-obfuscator@2.6.0
vue.config.js
- const CompressionPlugin = require('compression-webpack-plugin'); // gzip压缩,无关可忽略
-
- const TerserPlugin = require('terser-webpack-plugin');
- const WebpackObfuscator = require('webpack-obfuscator');
-
- const name = process.env.VUE_APP_TITLE || '*****' // 网页标题
-
- module.exports = {
- // ......
- configureWebpack: config => {
- const plugins = [
- // gzip压缩,无关可忽略
- new CompressionPlugin({
- cache: false,
- test: /\.(js|css|html)?$/i,
- filename: '[path].gz[query]',
- algorithm: 'gzip',
- minRatio: 0.8
- })
- ];
-
- if (process.env.NODE_ENV === 'production') {
- // 使用 Terser 进行代码压缩和 source map 生成
- config.optimization = {
- minimizer: [
- new TerserPlugin({
- terserOptions: {
- compress: {
- warnings: false,
- drop_console: true, // 开启console.log压缩
- drop_debugger: true, // 移除debugger
- },
- sourceMap: true, // 启用 source map 生成
- },
- extractComments: false, // 是否将注释提取到单独的文件中
- }),
- ],
- };
-
- // 在 Terser 之后使用 WebpackObfuscator 进行混淆
- plugins.push(
- new WebpackObfuscator(
- {
- // 压缩代码
- compact: true,
- // 通过用空函数替换它们来禁用console.log,console.info,console.error和console.warn。这使得调试器的使用更加困难。
- disableConsoleOutput: true,
- // 通过固定和随机(在代码混淆时生成)的位置移动数组。
- rotateStringArray: true,
- // 标识符的混淆方式 hexadecimal(十六进制) mangled(短标识符)
- identifierNamesGenerator: 'hexadecimal',
- },
- []
- )
- );
- }
-
- return {
- name: name,
- devtool: 'source-map', // 确保 devtool 设置为 'source-map' 或类似选项
- plugins: plugins
- };
- },
- }

VueCli4 对应 webpack-obfuscator@2.6.0
npm install --save-dev javascript-obfuscator webpack-obfuscator@2.6.0
① 使用 Terser 进行代码压缩和 source map 生成,
② 在 Terser 之后使用 WebpackObfuscator 进行混淆。
单独使用WebpackObfuscator的话,打包时就会一直报错(sourceAndMap):
① 以函数形式配置configWebpack
(注意Terser和WebpackObfuscator引入的方式不同,后者是放到plugins中)
② 设置在生产环境中才去使用混淆加密工具(开发环境会产生各种报错)
因版本问题导致花了很多时间研究并处理报错,版本对应很重要。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。