gulp的使用

什么是gulp

简单来说gulp就是一个前端的工作流工具。侧重于工作流

gulp的实质

gulp就是用js写了一个脚本文件gulpfile.js,把所有流程都用js来实现

gulp如何使用

gulp的使用简单来说就是:
装gulp,装gulp插件,抄gulp插件文档上的例子放到gulpfile里面,最后npm run一下就可以用了。(具体过程太麻烦了,上面的流程就是最精简的了)

举例说明

以下是我一个项目中的gulpfile.js文件:

var gulp = require('gulp');
var del = require('del');
var postcss = require('gulp-postcss');
const babel = require('gulp-babel');
var minify = require('gulp-minify');
gulp.task('rm', function() {
    // You can use multiple globbing patterns as you would with `gulp.src`
  return del(['dist/**']);
});
gulp.task('css',['rm'], function () {
    var postcss      = require('gulp-postcss');
    var sourcemaps   = require('gulp-sourcemaps');
    var autoprefixer = require('autoprefixer');
  return gulp.src('./src/*.css')
        .pipe(sourcemaps.init())
        .pipe(postcss([ autoprefixer() ]))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('./dist'));
});
gulp.task('css-watch', function () {
    var postcss      = require('gulp-postcss');
    var sourcemaps   = require('gulp-sourcemaps');
    var autoprefixer = require('autoprefixer');
    return gulp.src('./src/*.css')
        .pipe(sourcemaps.init())
        .pipe(postcss([ autoprefixer() ]))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('./dist'));
});
gulp.task('js',['rm'], () =>
    gulp.src('src/*.js')
        .pipe(babel({
            presets: ['env']
        }))
        .pipe(minify({noSource:true,  ext:{min:'.js'}}))
        .pipe(gulp.dest('dist'))
);
gulp.task('js-watch', () =>
    gulp.src('src/*.js')
        .pipe(babel({
            presets: ['env']
        }))
        .pipe(minify({noSource:true,  ext:{min:'.js'}}))
        .pipe(gulp.dest('dist'))
);
gulp.task('watch',function(){
    var watcher1 = gulp.watch('src/**/*.js', ['js-watch']);
    watcher1.on('change', function(event) {
        console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
    var watcher2 = gulp.watch('src/**/*.css', ['css-watch']);
    watcher2.on('change', function(event) {
        console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
})
gulp.task('default',['rm','css','js'])

你可能感兴趣的:(gulp的使用)