xvno / blog

个人博客, 不定期发布技术笔记和个人随笔.
0 stars 0 forks source link

Tools: Gulp: v4 #76

Open xvno opened 4 years ago

xvno commented 4 years ago

Refs

是什么

image

A toolkit to automate & Enhance your workflow Leverage gulp & the flexibility of JS to automate the slow & repetitive workflows and compose them into efficient build pipelines. 利用Gulp和JS的灵活性来使原本缓慢重复的工作流实现自动化, 并把他们编排为高效的流水线.

xvno commented 4 years ago

怎么用

  1. 全局安装 gulp-cli
  2. 编写 Gulpfile
  3. 使用 gulp [taskname] 命令运行 gulp tasks

1. 全局安装 nig gulp-cli

2. 编写Gulpfile

Gulpfile是什么

置于项目文件夹下, 命名为Gulpfile或gulpfile的文件, 会在执行命令gulp的时候自动载入的一个配置文件. 当然可以通过命令参数 --gulpfile-f 来指定其他名字/路径的文件.

文件框架

function taskUne(done) {
  // do sth here
  done() // remember to call `done()`
}

exports.default = taskUne

3. 运行任务

###### gulp 裸命令, 执行gulpfile.js导出的默认命令
gulp
###### gulp -f <gulpfile> <taskUne> <taskDuex>
gulp -f gulpit.js init clean
xvno commented 4 years ago

Tasks

Task是一个异步的JS function: 分为两类, 第一类 参数是一个回调函数的普通函数, 该回调函数的首参是个error; 第二类是一个返回 stream, promise, event emitter, child process, or observerable 的普通函数.

任务也有public 和 private之分, 区别在于是否被Gulpfile导出, 即 module.exports 中表明的任务为public, 否则为private.

(gulp.task()仍然没有被废止, 但建议export的方式优先)

Compose Tasks

串行, 并行; 并用该API组合小任务为更大的任务

function init(done){
  // done...
}

function clearup(done){
  // clear up
}

function clearCSS(done){
}
function clearES(done){
}

function compile(done){
  // exactly, complex jobs get done here
}

function build(done){
  // minimizing, packing target sources
}

const compileCSS = series(clearCSS, function(done){/* compile CSS */});
const compileES = series(clearES, function(done){/* compile ES */});
const compile = parallel(compileCSS, compileES);

module.export = {
  dist: series(clearup, init, parallel(complieCSS, compileES), build),
  dev: series(init, parallel(clearCSS, clearES), compile),
  compileCSS,
  compileES,
  clearCSS,
  clearES
}
xvno commented 4 years ago

src() & dest() 以及他们的 .pipe() 方法

Task的返回值可以为 stream, promise, event emitter, child process, or observerable之一, 所以 task可以直接返回一个src().pipe()生成的 stream

src(glob)

根据glob找到所有匹配的文件, 并读取到内存中以Node Stream的形式存在. 并能使用 .pipe() 来传递下去, 形成一个pipeline

dest(glob)

用在pipeline的中或结尾: 把流中的文件输出到glob匹配的路径 (含 md -p 操作), 并把当前流中的内容继续传递.

xvno commented 4 years ago

插件Plugins

是什么

Gulp的插件是封装好的处理过程, 用来改变pipeline中的文件 content/meta/name 插件名一般模式 gulp-<spec-name>

常见插件

xvno commented 4 years ago

gulp.watch

Events

all: add, addDir, change, unlink, unlinkDir ready, error

形式

const { watch } = require('gulp')

function watchit() {
  watch(glob | Array<glob>, { events: String | Array<String>, ignoreInitial: Boolean, queue: Boolean, delay: Integer}, cb | series() | parallel() )
}