自动构建 grunt gulp

Posted coderlin_

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自动构建 grunt gulp相关的知识,希望对你有一定的参考价值。

常用的自动化构建工具

Grunt
Gulp
Fls

Grunt


基本用法

Grunt的配置方法

initConfig支持注册一些参数。

module.exports = (grunt) => 
    grunt.initConfig(
        foo: 
            bar: 213
        
    )
    grunt.registerTask('test',()=>
       const bar =  grunt.config('foo')
       console.log(bar);
    )

多任务目标

module.exports = (grunt) => 
  grunt.initConfig(
    build: 
      css: "1",
      js: "2",
    ,
  );
  //多目标模式,可以让任务根据配置形成多个子任务
  grunt.registerMultiTask("build", function () 
      console.log(grunt.config('build'));
      console.log(`target $this.target, data: $this.data`);
  );

通过registerMultiTask和initConfig搭配,可以让任务执行多次
打印结果:

yarn grunt build
Running "build:css" (build) task
 css: '1', js: '2' 
target css, data: 1

Running "build:js" (build) task
 css: '1', js: '2' 
target js, data: 2

Done.
Done in 0.59s.
插件使用
yarn add grunt-babel @babel/core @babel/preset-env load-grunt-tasks -D
const loadGruntTaks = require("load-grunt-tasks");
module.exports = (grunt) => 
  grunt.initConfig(
    babel: 
      // options配置
      options: 
        presets: ["@babel/preset-env"],
      ,
      // 设置任务
      main: 
        files: 
          //文件路径
          "dist/js/index.js": "index.js", //输出:输入
        ,
      ,
    ,
    sass: 
      options: 
        sourceMap: true,
        implementation: sass,
      ,
      main: 
        file: 
          "dist/css/main.css": "index.scss",
        ,
      ,
    ,
  );

  // grunt.loadNpmTasks('grunt-babel')
  loadGruntTaks(grunt); //自动加载grunt插件中的任务
 

如上,通过loadGruntTasks加载插件,通过initConfig定义任务,并且配置相关的配置。
如yarn grunt script,转化js文件的时候

原本这样
const a = new Promise((r) => 
  setTimeout(() => 
    r(123);
  , 2000);
);

转化后

"use strict";

var a = new Promise(function (r) 
  setTimeout(function () 
    r(123);
  , 2000);
);

Gulp

Gulp与webpack

  • Gulp更像是一个任务调度器,它本身什么都做不了,开发者需要自己定制任务去完成(pipe())
  • webpack是一个模块化打包器,统一入口。从本质上来说,他们不应该放在一起去比较。只是webpack一直在突破自己的边界,做了很多gulp都能做得事情。
基本使用
//gulpfile.js

exports.foo = (done) => 
    console.log('foo task working');

    done() //标识任务完成



exports.default = (done) => 
    console.log('default task working');

    done() //标识任务完成

打印

yarn gulp
[13:07:45] Using gulpfile ~\\Desktop\\学习\\项目汇总3\\lg\\工程化\\Gulp\\gulpfile.js
[13:07:45] Starting 'default'...
default task working
[13:07:45] Finished 'default' after 1.89 ms
Done in 1.40s.
创建组合任务

series创建串行的任务,parallel创建并行的任务

const  series, parallel  = require('gulp')

const task1 = (done) => 
  setTimeout(() => 
    console.log("task1 working");
    done();
  , 1000);
;

const task2 = (done) => 
  setTimeout(() => 
    console.log("task2 working");
    done();
  , 2000);
;

const task3 = (done) => 
  setTimeout(() => 
    console.log("task3 working");
    done();
  , 3000);
;

exports.foo = series(task1, task2, task3) //串行

exports.bar = parallel(task1, task2, task3) //并行
异步任务
// 普通异步回调
exports.callback = (done) => 
  console.log("callback task");
  done(new Error("task failed")); //错误优先回调
;

//promise异步
exports.promise = () => 
  console.log("promise task");
  return new Promise((r, j) => 
    setTimeout(() => 
      r(123);
    , 2000);
  );
;

const timeout = (time) => 
  return new Promise((r) => 
    setTimeout(() => 
      r(time);
    , time);
  );
;

// async await异步
exports.async = async () => 
  const timeout1 = await timeout(3000);
  console.log("timeout", timeout1);
;

// 流异步
const fs = require('fs')
exports.stream = done => 
    const readSteam = fs.createReadStream('package.json')
    const writeStream = fs.createWriteStream('temp.txt')
    readSteam.pipe(writeStream)
    return readSteam //当可读流触发end事件之后,任务结束。相当于如下
    readSteam.on('end', ()=>
        done()
    )
;

四种异步流程,普通回调,Pormise,async+await,stream。

构建过程核心工作原理

the streaming build system(流构建系统)

  • 通过读取流,fs.createReadStream先数据读取出来,通过pipei流向TransForm实例,进行转换,然后再通过pipe流向可写流fs.createWriteStream。
  • 读取流=》转换流=》可写流
const fs = require('fs')
const Transform  = require('stream')
exports.default = done => 
    const readSteam = fs.createReadStream('package.json')
    const writeStream = fs.createWriteStream('temp.txt')
    const transform = new Transform(
        transform: (chunk, encoding, callback)=>
            const input = chunk.toString()
            const output = input.replace(/\\s+/g, '').replace(/\\/\\*.+?\\*\\//g, '')
            callback(null, output)
        
    )
    readSteam.pipe(transform).pipe(writeStream)
    return readSteam

文件操作API+插件的使用
const  src, dest  = require("gulp");
const cleanCss = require("gulp-clean-css"); //压缩
const rename = require("gulp-rename"); // 重命名文件夹
// src读取,支持通配符
// dest输出
exports.default = () => 
  return src("src/*.css")
    .pipe(cleanCss())
    .pipe(rename( extname: ".min.css" ))
    .pipe(dest("dist"));
;

demo

const  src, dest  = require("gulp");

//样式编译
const style = (done) => 
  // 加上base之后,比如base是src,那么后面的/assets/styles就会被保留下来
  return src("src/assets/styles/*.less",  base: "src" ).pipe(dest("dist"));
;

const babel = require("gulp-babel");
//js编译
const script = () => 
  return src("src/assets/scripts/*.js",  base: "src" )
    .pipe(babel( presets: ["@babel/preset-env"] ))
    .pipe(dest("dist"));
;

module.exports = 
  style,
  script,
;

通过插件编译less和js文件。

FIS

相比于grunt和gulp, Fis高度集成。有兴趣可以看官网

以上是关于自动构建 grunt gulp的主要内容,如果未能解决你的问题,请参考以下文章

前端工作流程自动化——Grunt/Gulp 自动化

gulp和grunt的区别

自动化构建工具Gulp初体验

前端自动化:谈谈grunt和gulp的区别

前端自动化构建工具-gulp

前端构建工具Gulp.js 你知多少..(webpack/gulp/grunt)