# gulp

# 1. 入门指南

# 1.1. 快速入门

官网:

https://www.gulpjs.com.cn/ (opens new window)

安装:

npm install --global gulp-cli

npm i gulp

gulp -v    
# CLI version: 2.3.0
# Local version: 4.0.2

创建 gulpfile.js 文件:

// proj/gulpfile.js

exports.default = function() { /* ... */ };
exports.build = function() { /* ... */ };

执行构建:

# 等价于:gulp default
gulp

gulp build

# 1.2. 任务

const { series, parallel } = require('gulp');

function task1(cb) {
  cb();
  console.log('task1...')
}
function task2(cb) {
  cb();
  console.log('task2...')
}
function task3(cb) {
  cb();
  console.log('task3...')
}

// 顺序执行
exports.default = series(task1, task2, task3);

// 并发执行
exports.build = parallel(task1, task2, task3);

# 1.3. 异步执行

任务返回 promise、stream、event emitter、child process 或 observable

如果没有返回值,则使用 callback

# 1.4. 处理文件

const { src, dest } = require('gulp');
const babel = require('gulp-babel');

exports.default = function() {
  // 读取文件
  return src('src/*.js')
    .pipe(babel())
    // 写到 output 目录
    .pipe(dest('output/'));
}

# 2. 插件

# 2.1. gulp-clean

const { src } = require('gulp');
const clean = require('gulp-clean');

module.exports = function() {
  return (
    src(
      './**/*', // 所有文件及目录
      {
        cwd: './dist/', // 工作目录
        read: false,    // 不需要读取文件内容
        dot: true,      // 以 . 打头的文件也包含
      }
    )
      .pipe(clean())
  );
}

注意:

  • 出现莫名其妙的问题,建议使用 fs.rmSync()

# 2.2. gulp-rename

const { src, dest } = require('gulp');
const rename = require('gulp-rename');

function build() {
  return src(`src/images/**/*.png`, { cwd: CTX_PATH })

    // 1600/guns/AMK.png -> 1600/AMK.png
    .pipe(rename(function (path) {
      // { dirname: '1600\\guns', basename: 'ACVAL', extname: '.png' }
      const { dirname } = path;

      const dirs = dirname.split(/[/\\]/);

      const firstDir = dirs[0] || '';

      path.dirname = firstDir;
    }))

    .pipe(dest(TCG_IMAGES_DIR));
}

# 2.3. gulp-typescript


const { src, dest } = require('gulp');
const ts = require('gulp-typescript');
const tsProject = ts.createProject('tsconfig.json');

function build() {
  return src('src')
    .pipe(tsProject()).js
    .pipe(dest('dist'));
}

module.exports = build;
本章目录