I. environmental preparation
1.1 introduction to gulp
- gulp is a front-end automatic construction tool based on the file flow of node.js. It can be used to build automatic workflow and simplify workload
- Official definition: build system based on file flow
- Core files: gulpfile.js and package.json
- gulpfile.js: task script
- package.json: task configuration file
1.2 install gulp
npm install gulp -g
1.3 build project
- (1) switch to the root directory of the project (that is, the directory where gulpfile.js is located). The package that the command line installation task depends on: npm install
- (2) after installation, you can directly execute the command: gulp
2. Use instance package js and css
2.1 reference in package.json depends on gulp minify CSS and gulp uglify
"devDependencies": { "del": "^2.2.2", "gulp": "^3.9.1", "gulp-header": "^1.8.8", "gulp-minify-css": "^1.2.4", "gulp-replace": "^0.6.1", "gulp-uglify": "^1.5.4" }
2.2 define our first gulp process
var pkg = require('./package.json'); var del = require('del'); var gulp = require('gulp'); var uglify = require('gulp-uglify'); var minify = require('gulp-minify-css'); var replace = require('gulp-replace'); var header = require('gulp-header'); // Defining tasks var destDir = './dist' // Build target directory ,note = [// Notes '/** <%= pkg.name %>-v<%= pkg.version %> <%= pkg.license %> License By <%= pkg.homepage %> */\n <%= js %>' ,{pkg: pkg, js: ';'} ] ,task = { minjs: function(){// Compress JS var src = [ './src/**/*.js' ,'!./src/config.js'// ! Indicates that the file is not compressed ]; return gulp.src(src).pipe(uglify())// Using the compression tool .pipe(header.apply(null, note)) .pipe(gulp.dest(destDir)); } ,mincss: function(){// Compress CSS var src = [ './src/**/*.css' ] ,noteNew = JSON.parse(JSON.stringify(note)); noteNew[1].js = ''; return gulp.src(src).pipe(minify({ compatibility: 'ie7' })).pipe(header.apply(null, noteNew)) .pipe(gulp.dest(destDir)); } ,mv: function(){// Copy folder gulp.src('./src/config.js') .pipe(gulp.dest(destDir)); return gulp.src('./src/views/**/*') .pipe(gulp.dest(destDir + '/views')); } }; // Clean-up work gulp.task('clear', function(cb) { return del(['./dist/*'], cb); }); // Building entrance gulp.task('default', ['clear', 'src'], function(){ for(var key in task){ task[key](); } });
2.3 build output
[13:31:17] Using gulpfile .\xxx\gulpfile.js [13:31:17] Starting 'clear'... [13:31:17] Starting 'src'... [13:31:17] Finished 'src' after 11 ms [13:31:17] Finished 'clear' after 57 ms [13:31:17] Starting 'default'... [13:31:17] Finished 'default' after 5.26 ms