1. New Project
The project structure is as follows:
/app
-- /js
-- /css
/dist
-- /js
-- /css
-- index.html
gulpfile.js
Our code is developed in the / app directory and saved in / dist after transcoding, merging, compressing.
2. Configuring the environment
(1) Initialize npm
First enter the root directory and initialize the project
npm init
(2) installing gulp and its dependencies
//Install gulp
npm install gulp --save-dev
//Install ES6 Transcoder, ES6 code to ES5 code
npm install gulp-babel babel-preset-es2015 babel-core --save-dev
//Other Tools
npm install gulp-rename gulp-concat gulp-uglify gulp-cssnano browserify vinyl-source-stream --save-dev
gulp-rename
rename file
gulp-concat
Merge Files
gulp-uglify
Compress js files
gulp-cssnano
Compress css file
browserify
Allows you to organize browser-side Javascript code in a node like require()
vinyl-source-stream
Converts the output of a bundle() from Browserify to a vinyl (a virtual file format) stream available to Gulp
The environment has been built.Next we need to configure gulp to make our work more efficient.
3. Configuring gulp
Create gulpfile.js in the root directory for configuration
const gulp = require('gulp');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const cssnano = require('gulp-cssnano');
const concat = require('gulp-concat');
const browserify = require('browserify');
const source = require('vinyl-source-stream');
// Compile and Compress js
gulp.task('convertJS', function(){
return gulp.src('app/js/*.js')
.pipe(babel({
presets: ['es2015']
}))
.pipe(uglify())
.pipe(gulp.dest('dist/js'))
})
// Merge and Compress css
gulp.task('convertCSS', function(){
return gulp.src('app/css/*.css')
.pipe(concat('app.css'))
.pipe(cssnano())
.pipe(rename(function(path){
path.basename += '.min';
}))
.pipe(gulp.dest('dist/css'));
})
// Monitor file changes and perform tasks automatically
gulp.task('watch', function(){
gulp.watch('app/css/*.css', ['convertCSS']);
gulp.watch('app/js/*.js', ['convertJS', 'browserify']);
})
// browserify
gulp.task("browserify", function () {
var b = browserify({
entries: "dist/js/app.js"
});
return b.bundle()
.pipe(source("bundle.js"))
.pipe(gulp.dest("dist/js"));
});
gulp.task('start', ['convertJS', 'convertCSS', 'browserify', 'watch']);
With watch, we can have gulp automatically build the code for us once we've saved it, instead of typing the command again.
Start gulp
gulp start
You can simply use bundle.js