Gulp 详解

Gulp 详解

安装

  1. 准备工作

    # 全局安装
    npm install gulp-cli -g
    
    # 或者使用 yarn 全局安装
    yarn global add gulp-cli
    
    # 项目依赖包
    npm install gulp -D
    
    # 使用 yarn 安装依赖包
    yarn add -D gulp
    

创建 gulpfile.js 文件

touch gulpfile.js
  1. 使用 commonjs 规范编写脚本
// gulp 4.0 改成了异步任务
async function foo() {
  const msg = "foo task working";

  console.log(msg);

  await Promise.resolve(msg);
}

exports.foo = foo;

// 不再推荐的写法
const gulp = require("gulp");
gulp.task("bar", (next) => {
  console.log("bar working");

  next();
});

组合任务

  1. 串行任务

    const { series } = require("gulp");
    
    // The `clean` function is not exported so it can be considered a private task.
    // It can still be used within the `series()` composition.
    function clean(cb) {
      // body omitted
      cb();
    }
    
    // The `build` function is exported so it is public and can be run with the `gulp` command.
    // It can also be used within the `series()` composition.
    function build(cb) {
      // body omitted
      cb();
    }
    
    exports.build = build;
    exports.default = series(clean, build);
    
  2. 并行任务

    const { parallel } = require("gulp");
    
    function javascript(cb) {
      // body omitted
      cb();
    }
    
    function css(cb) {
      // body omitted
      cb();
    }
    
    exports.build = parallel(javascript, css);
    

Gulp 的工作原理就是流的操作

const fs = require("fs");
const { Transform } = require("stream");

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

  read.pipe(transform).pipe(write);

  return read;
};

Gulp 文件操作 API 实例

const { series, src, dest } = require("gulp");
const gulpClean = require("gulp-clean");
const clean = require("gulp-clean");
const cleanCSS = require("gulp-clean-css");
const rename = require("gulp-rename");

function cleanPath() {
  return src("./dist").pipe(gulpClean());
}

function styleConvert() {
  return src("src/*.css")
    .pipe(cleanCSS({ compatibility: "ie8" }))
    .pipe(
      rename({
        extname: ".min.css",
      })
    )
    .pipe(dest("dist"));
}

exports.default = series(cleanPath, styleConvert);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值