How to use Gulp
Gulp is a cross-platform, streaming task runner that lets developers automate many development tasks such concatenate js files, minifying js and css files, optimizing images e.t.c.
Firstly install gulp cli:
# without sudo not working on MacOs
sudo npm install --global gulp-cli
Then
- go to project directory
- install all necessary plugins
- add gulpfile.js where the gulp tasks are listed
- execute gulp
cancating and minify
With this example you can concat and minify usual js files (not modules) and css files.
1. Install gulp with concat plugin:
npm install --save-dev gulp gulp-concat
2. Install gulp plugins for minify javascripts and css files:
npm install --save-dev gulp-clean-css gulp-minify
Or if you use es6 syntax:
npm install --save-dev gulp-uglify-es
3. Add the gulpfile.js file with following content:
var gulp = require('gulp');
var concat = require('gulp-concat');
//- var minify = require('gulp-minify');
//+ minify with es6 support
var uglify = require('gulp-uglify-es').default;
var cleanCss = require('gulp-clean-css');
// Suppose you have js/src with your js, it can contains subdirectory.
// Suppose you have a js/vendor directory for code from vendors.
gulp.task('pack-js', function() {
return gulp.src(['js/vendor/file-saveas-min.js', 'js/src/**/.js'])
.pipe(concat('bundle.js'))
//.pipe(minify())
.pipe(uglify())
.pipe(gulp.dest('dist/js'));
});
// assume you have css directory with mycss1.css and mycss2.css files
gulp.task('pack-css', function() {
return gulp.src(['css/mycss1.css', 'css/mycss2.css'])
.pipe(concat('mycss-min.css'))
.pipe(cleanCss())
.pipe(gulp.dest('dist/css'));
});
// old
// gulp.task('default', ['pack-js', 'pack-css']);
// gulp 4.0+
gulp.task('default', gulp.series('pack-js', 'pack-css'));
4.Execute gulp:
gulp
useful plugins and modules for gulp
# module for logging
npm install --save-dev fancy-log
# gulp 3.0 plugin for replacing string in .pipe
npm install --save-dev gulp-replace