Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Gulp task for uglify with npm script

Tags:

npm

gulp

Currently I am using npm for package management and Gulp for running tasks. I am wondering if I am able to use npm scripts to replace gulp and use only npm.

My gulpfile.js for uglifying looks as following

var uglify = require('gulp-uglify');

// Minify JS
gulp.task('minify-js', function() {
 return gulp.src('js/agency.js')
 .pipe(uglify())
 .pipe(header(banner, { pkg: pkg }))
 .pipe(rename({ suffix: '.min' }))
 .pipe(gulp.dest('js'))
 .pipe(browserSync.reload({
 stream: true
 }))
});

Is there a way to write a equivalent script in npm?

like image 617
Happy Avatar asked Dec 10 '16 10:12

Happy


People also ask

What is Uglify in JavaScript?

Uglify JS is a JavaScript library for minifying JavaScript files. To 'uglify' a JavaScript file is to minify it using Uglify. Uglification improves performance while reducing readability. Encryption: This is the process of translating data, called plain data, into encoded data.


1 Answers

First, I recommend you to have two directories src and dist.

  • src contains raw code before any minifications made, it is used to read and edit your code.
  • dist stands for distribution and contains minified and concatenated version of your code, it is used on production sites.

Step 1

You can use uglify-js to combine and minify your JavaScript files.

Install it with following command:
npm install --save-dev uglify-js

Step 2

In your package.json file set new task called uglify:

"scripts": {
  ...
  "uglify": "mkdir -p dist/js && uglifyjs src/js/*.js -m -o dist/js/app.js && uglifyjs src/js/*.js -m -c -o dist/js/app.min.js"
}

Explanation

The first half of this task, mkdir -p dist/js creates a folder structure (mkdir), but only if it doesn't exist already (-p flag). Once that completes successfully, run the uglifyjs command. The && lets you chain multiple commands together, running each one sequentially if the previous command completes successfully.

The second half of this task tells uglifyjs to start with all of the JS files (*.js) in src/js/, apply the "mangle" command (-m flag), and output the result to dist/js/app.js.

And to create a compressed version of dist/js/app.js we chain another uglifyjs command and passing the "compress" (-c) flag.

like image 123
rand0rn Avatar answered Sep 28 '22 08:09

rand0rn