Uglyfy top level functions with gulp

Take this simple gulp example for uglification:

gulp.task('scripts', function() { // Minify and copy all JavaScript (except vendor scripts) return gulp.src(paths.scripts) .pipe(uglify()) .pipe(concat('all.min.js')) .pipe(gulp.dest('build/js')); }); 

If you have two files:

f1.js file:

 function f1(){ var hello = 1; return hello; } 

f2.js file:

 function f2(){ return f1(); } 

The result of the task in all.min.js is:

 function f1(){var n=1;return n} function f2(){return f1()} 

How can I make uglify cripple these top-level function names, i.e. f1 and f2 ? I tried:

Optional uglify

 return gulp.src(paths.scripts) .pipe(uglify()) .pipe(concat('all.min.js')) .pipe(gulp.dest('build/js')) .pipe(uglify()); 

Passing the mangle option

 return gulp.src(paths.scripts) .pipe(uglify({mangle: true})) .pipe(concat('all.min.js')) .pipe(gulp.dest('build/js')); 

Top level transfer

 return gulp.src(paths.scripts) .pipe(uglify({toplevel: true})) .pipe(concat('all.min.js')) .pipe(gulp.dest('build/js')); 

But all this has no effect.

+6
source share
2 answers
 .pipe(uglify({mangle: {toplevel: true}})) 
+6
source

It seems that uglify will not distort the names of functions that are global variables (even with the "mangle" and toplevel set to true at the same time). Doing this in any case would seem impractical, since any event handlers in your HTML will not work after fading, and you could not (easily) call functions from the console, since the name probably changed. If this is not important for you, try wrapping your code in the function area:

 (function(){ // your code here... }()); 

This uglify method will distort function names.

You can also try one of the obfuscate plugins for Gulp when it comes to the inaccessibility of your script.

+5
source

Source: https://habr.com/ru/post/971150/


All Articles