|
| 1 | +"use strict"; |
| 2 | + |
| 3 | +declare let module: any; |
| 4 | +declare let require: any; |
| 5 | + |
| 6 | +let multimatch: any = require('multimatch'), |
| 7 | + JavaScriptObfuscator = require('javascript-obfuscator'); |
| 8 | + |
| 9 | +class WebpackObfuscator { |
| 10 | + public options: any = {}; |
| 11 | + public excludes: string[]; |
| 12 | + |
| 13 | + private PLUGIN_NAME: string = 'webpack-obfuscator'; |
| 14 | + |
| 15 | + /** |
| 16 | + * @param options |
| 17 | + * @param excludes |
| 18 | + */ |
| 19 | + constructor (options: any, excludes: string|string[]) { |
| 20 | + this.options = options; |
| 21 | + this.excludes = typeof excludes === 'string' ? [excludes] : excludes || []; |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * @param compiler |
| 26 | + */ |
| 27 | + public apply (compiler: any): void { |
| 28 | + compiler.plugin('compilation', (compilation: any) => { |
| 29 | + compilation.plugin("optimize-chunk-assets", (chunks: any[], callback: () => void) => { |
| 30 | + let files = []; |
| 31 | + |
| 32 | + chunks.forEach((chunk) => { |
| 33 | + chunk['files'].forEach((file) => { |
| 34 | + files.push(file); |
| 35 | + }); |
| 36 | + }); |
| 37 | + |
| 38 | + compilation.additionalChunkAssets.forEach((file) => { |
| 39 | + files.push(file); |
| 40 | + }); |
| 41 | + |
| 42 | + files.forEach((file) => { |
| 43 | + let asset = compilation.assets[file]; |
| 44 | + |
| 45 | + compilation.assets[file] = JavaScriptObfuscator.obfuscate(asset.source(), this.options); |
| 46 | + }); |
| 47 | + |
| 48 | + callback(); |
| 49 | + }); |
| 50 | + }); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * @param filePath |
| 55 | + * @param excludes |
| 56 | + * @returns {boolean} |
| 57 | + */ |
| 58 | + private shouldExclude (filePath: string, excludes: string[]): boolean { |
| 59 | + for (let exclude of excludes) { |
| 60 | + if (multimatch(filePath, exclude).length > 0) { |
| 61 | + return true; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + return false; |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +module.exports = WebpackObfuscator; |
0 commit comments