Part2.4 gulp 实践

  • 文章内容输出来源:拉勾教育大前端训练营
// 取消同步,只有异步任务,需要回调函数结束任务
exports.foo=()=>{
    console.log("foo start")//报错 The following tasks did not complete: foo
}

//导出函数成员定义gulp任务
exports.foo=(done)=>{
    console.log("foo start")
    done()
}

//任务名称是default是默认执行的
//yarn gulp 
exports.default=(done)=>{
    console.log("dafault start")
    done()
}

const gulp=require("gulp")
const { series, parallel } = require("gulp")

//gulp 4.0之后 保留了注册任务的api,不推荐使用
gulp.task('bar',(done)=>{
    console.log('bar start')
    done()
})

const task1=done=>{
    console.log("任务1")
    done()
}
const task2=done=>{
    console.log("任务2")
    done()
}
const task3=done=>{
    console.log("任务3")
    done()
}
//串行任务
exports.foo1=series(task1,task2,task3)
//并行任务
exports.bar1=parallel(task1,task2,task3)

//回调函数/return Promise.resolve()对象不需要实参( gulp会忽略这个值 )使得任务成功
//通过回调函数传递实参new Error() 错误对象/return Promise.reject(new Error("failed")) 使得任务失败中断任务

//async await/Promise 处理异步
//stream 处理异步流程
const fs=require("fs")

// exports.stream=()=>{
//     const readStream=fs.createReadStream('package.json')
//     const wrtieStream=fs.createWriteStream("temp.txt")
//     readStream.pipe(wrtieStream)
//     return readStream
// }

exports.stream=(done)=>{
    const readStream=fs.createReadStream('package.json')
    const wrtieStream=fs.createWriteStream("temp.txt")
    readStream.pipe(wrtieStream)
    readStream.on('end',()=>{
        done()
    })
}
  • 构建过程核心工作原理 读取/转换/写入流
const fs = require("fs");
const { Transform } = require("stream");

exports.default = (done) => {
  const read = fs.createReadStream("mycss.css");
  const write = fs.createWriteStream("mycss.min.css");
  const transform = new Transform({
    transform: (chunk, encoding, callback) => {
      const input = chunk.toString();
      const output = input.replace(/\s+/g, "").replace(/\/\*.+?\*\//g, "");
      callback(null, output);
    },
  });
  read.pipe(transform).pipe(write);
  return read;
};

  • gulp文件压缩重命名插件使用
const { src, dest } = require("gulp");
const cleanCss=require('gulp-clean-css')
const rename=require('gulp-rename')
exports.default = () => {
  return src("mycss.css") //*.css
  .pipe(cleanCss())
  .pipe(rename({extname:'.min.css'}))
  .pipe(dest("dist"));
};
posted @ 2020-08-08 21:12  tony_zhu  阅读(143)  评论(0编辑  收藏  举报