由于从安全性考虑,项目在打包时,需要将暴露的 路由,接口地址进行混淆。因此我们借助 webpack-obfuscator 来实现。
代码如下
const path = require('path')
const JavaScriptObfuscator = require('webpack-obfuscator');
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: 'dist',
filename: path.posix.join('static', 'js/[name].[chunkhash].js'),
chunkFilename: path.posix.join('static', 'js/chunk-[id].[chunkhash].js') // 增加 chunk 方便混淆时,排除
},
optimization: {
minimize: true,
runtimeChunk: { name: 'runtime' },
concatenateModules: true,
splitChunks: {
chunks: "all", // chunks (async,initial,all)( async表示只从异步加载得模块(动态加载import())里面进行拆分 initial表示只从入口模块进行拆分 all表示以上两者都包括)
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'all',
priority: -10
},
'api': { // 将混淆的目标文件抽离打包
name: 'confuse-js',
test: path.resolve('src/http'),
priority: 50
},
'router': { // 将混淆的目标文件抽离打包
name: 'confuse-r',
test: path.resolve('src/router'),
priority: 50
}
},
},
moduleIds: 'deterministic'
},
plugins: [
new JavaScriptObfuscator({
controlFlowFlattening: true, // 控制流扁平化
controlFlowFlatteningThreshold: 1, // 0-1
shuffleStringArray: true, // 随机打乱stringArray数组
stringArrayThreshold: 1, // 0-1
stringArrayEncoding: ['base64'], // stringArray数组加密方式
splitStrings: true // 分割字符串
}, [ // 忽略的文件
'**/js/chunk-**.**.js',
'**/js/runtime.**.js',
'**/js/app.**.js',
'**/js/vendor.**.js']
)
]
}
常规的用法,不用多描述,webpack-obfuscator官方都有。主要记录一下 excludes 这个参数配置, 因为官方描述的并不是很清楚。
从官网可知该匹配规则使用 multimatch。
然后我们接下来看下 webpack-obfuscator 的关键源码
打印一下可以看到 fileName: static/js/chunk-798.4a24e436f216eb7cc715.js 然后通过 sholdExclude 判断是否继续往下走 。
shouldExclude 其实就是调用 multimatch. 如 multimatch(static/js/chunk-798.4a24e436f216eb7cc715.js, [ '**/js/chunk-**.**.js', '**/js/runtime.**.js', '**/js/app.**.js', '**/js/vendor.**.js'])
如果匹配到,则不进行下去。后面的混淆等利用的 javascript-obfuscator, 文档中包含详细的配置。
这样可以解决打包速度变慢的问题,如果对所有文件进行混淆,打包速度会慢很多倍,体积响应的也会增加很多倍。而只针对指定文件进行混淆我们可以发现增加时间并不会太多,体积变化也不大。