gulp-入门

*  此操作只适合于gulp3

gulp安装

  全局安装:npm install gulp -g
  项目内安装: npm install --save-dev gulp

gulp常用到的API

  gulp.src('') : 说白了就是你要编译的内容的位置

  gulp.dest(''): 就是你掏把编译过的内容存放的位置

  gulp.task(''):  新建任务

  gulp.watch(''): 监控任务

  gulp.start('');  开始任务 gulp4开始 不能用了

gulp常用的插件

  安装方式都是  npm install --save-dev gulp-插件名

  安装之后就可以在package.json文件 devDependencies目录下找到(顺便说一下 有时候gulp编译的时候出现bug,第一步应该先在这里看看插件安装成功与否)

  gulp-htmlmin: 其实就是html的编译

  gulp-sass: 其实就是css的编译

  gulp-changed: 只编译改动过的文件

  gulp-debug:可以看出来哪些文件进行过编译

我自己写的一个小demo:

下面是我的目录结构 :简单介绍一下   我把src-iframe-index.html文件编译过后放到src2-iframe下面, src-js-index.js文件编译过后放到src2-js下面

 

 

 

 

let gulp = require('gulp');

let changed = require('gulp-changed');
let htmlmin = require('gulp-htmlmin');
let debug = require('gulp-debug');

let htmlminOptions = {
    removeComments: true,
    collapseWhitespace: true,
    collapseBooleanAttributes: true,
    removeEmptyAttributes: true,
    removeScriptTypeAttributes: true,
    removeStyleLinkTypeAttributes: true,
    minifyJS: true,
    minifyCSS: true
};

gulp.task('copy-jslib', function () {
    return gulp.src('src/js/*').pipe(gulp.dest('src2/js/'));
});

gulp.task('copy', function () {
    gulp.start('copy-jslib')
})


gulp.task('iframehtml', function () {
    let srcHtml = 'src/iframe/*.html';
    let destHtml = 'src2/iframe/';
    return gulp
        .src(srcHtml)
        .pipe(changed(destHtml, {extension: '.html' }))
        .pipe(debug({ title: '【iframehtml编译】: ' }))
        .pipe(htmlmin(htmlminOptions))
        .pipe(gulp.dest(destHtml));
})

gulp.task('html', function () {
    gulp.start('iframehtml')
})

gulp.task('one', function (cb) {  // cb为任务函数提供的回调,用来通知任务已经完成
    setTimeout(function () {
        console.log('one is done')
        cb();  // 执行回调,表示这个异步任务已经完成
    }, 5000)
})

// 这时two任务会在one任务中的异步操作完成之后再执行
gulp.task ('two', ['one'], function () {
    console.log('two is done');
})


gulp.task('default', function () {
    gulp.start('copy', 'html', 'one', 'two')
})

 

 

 

简单介绍一下其实很简单的 大家应该都能看的懂:
  1.引入gulp以及各种作用的插件
  2.创建任务
  gulp.task('创建任务名称', function () {
    return 执行的操作 gulp.src('开始目录').pipe(gulp.dest('编译后的目录'))
  }) 
  3. 启动任务
  gulp.task('任务名称', function () {
    gulp.start('创建任务名称')
  })
  4.要有一个默认的启动项
  gulp.task('default', function () {
    gulp.start('任务名称'')
  })
 
最后总结一下:
  我是最近在学习gulp,查了很多资料然后有了一点自己的理解,我自己验证过是可以用的,所以想发出来给大家一点参考,如果觉得有什么不对的地方希望可以评论我们一起研究,不喜欢也不要喷我哈,我的初衷只是为了让自己加深印象  仅此而已

 

posted @ 2020-12-17 14:07  壮壮~  阅读(164)  评论(1编辑  收藏  举报