Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

File f1.js:

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

File f2.js:

function f2(){
  return f1();
}

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

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

How can I get uglify to mangle these top level function names i.e. f1 and f2? I have tried:

An extra uglify

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

Passing mangle option

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

Passing top level option

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

But all to no effect at all.

like image 728
weston Avatar asked Jun 21 '14 18:06

weston


People also ask

What does gulp uglify do?

gulp uglify transmits a 'blunder' occasion in the event that minifying a particular file can't.

How do you use Terser in Gulp?

We can also use a third-party minifer and source-map as per our requirements as follows. const gultp = require('gulp'); const terserr = require('terser'); const terserg = require('gulp-terser') function ess(){ return gulp. src('Gulp/Demo/home.


2 Answers

.pipe(uglify({mangle: {toplevel: true}}))
like image 84
starikovs Avatar answered Oct 18 '22 01:10

starikovs


It seems uglify will not mangle function names that are global variables (even with 'mangle' and toplevel parameters set to true at the same time). Doing this would seem quite impractical to me anyway, as any event handlers in your HTML wouldn't work after uglifying anymore and you couldn't (easily) invoke functions from the console either, as the name has probably changed. If that is of no matter to you, try wrapping your code in a function scope:

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

This way uglify will mangle the function names.

You could also try one of the obfuscate plugins for Gulp if it is about making your script inaccessible.

like image 5
christian314159 Avatar answered Oct 18 '22 00:10

christian314159