In the front-end engineering applications gulp4 in

Foreword

    Bloggers recently ready to develop a UI component library, encountered a problem, bloggers want to pack a separate component style scss file, rather than using webpack components packaged together. Research found that gulp can solve this problem, then studied under gulp4 application front end engineering of.

1 Introduction

     gulp is a flow-based automation tool to build, based nodeJs the Stream (stream) to read and write data with respect to grunt directly read and write the file IO is faster.
    By means of GULP, we can complete the automated js / sass / less / css testing file, checking, merging, compression, formatting, and monitor these steps are repeated a specified file after alteration.
    gulp and webpack biggest difference is reflected in gulp and not as the css / less / image resources and other non-js class modular package like webpack.
    gulp application scenarios: individually packaged sass / less / css, compressing images, html compression and so on.

2. Install gulp

Global installed gulp

$ npm install gulp -g

As development projects dependent (devDependencies) Installation:
$ npm install gulp --save-dev

View gulp version ( Note: gulp3 with a larger difference gulp4, please refer to the article section 4 )
$ gulp -v
CLI version: 2.2.0
Local version: 4.0.2

New gulpfile.js
// 定义default任务(gulp4)
gulp.task('default', async() => { 
    await ...
});
复制代码

Execution GULP (default default task execution)

$ gulp

3. Common API

  • gulp.src (globs [, options])
    files in the directory read
  • gulp.dest (path [, options])
    is written to the file directory
  • gulp.task (name [, deps], fn)
    defines a task gulp
  • gulp.pipe ()
    object file by plug-in processing
  • gulp.watch (glob [, opts], tasks) or gulp.watch (glob [, opts, cb ])
    monitoring the file system, and may perform operations when changes occur in the file
  • gulp.series (task1, task2, task3) (gulp4 new)
    serial mission
  • gulp.parallel (task1, task2, task3) (gulp4 new)
    parallel execution of tasks

4.gulp3 and glup4

gulp3 and change gulp4, mainly reflected changes in the task definition and implementation of the system.

4.1gulp3 the task definition and execution order

For gulp3 task, the task sequence completed the task execution depends only perform the task.

gulp3 the task definition:

// gulpfile.js文件
const gulp = require('gulp');

// 定义task1任务
gulp.task('task1', function() {
  console.log('task1');
});

// 定义task2任务
gulp.task('task2', function() {
  console.log('task2');
});

// 定义default任务,依赖于task1任务和task2任务
gulp.task('default', ['task1', 'task2'], function() {
  console.log('done');
});
复制代码

gulp3 tasks executed:

execution order:
Start Task1 => Finish Task1 => Start Task2 => Finish Task2 => Start default => default Finish

4.2gulp4 the task definition and execution order

gulp4 in the gulp3 task definition is no longer dependent on support and implementation.
Consider the definition of the task still use gulp3 way:

gulp.task('task1', function() {
  console.log('task1');
});
复制代码

Execution task1, an error Did you forget to signal async completion?

Solution: using async await define tasks,

// 定义task1任务
gulp.task('task1', async() => {
  await console.log('task1');
});
复制代码

Perform task1, mission successful.

gulp4 task execution is no longer used in the implementation-dependent, instead of using the serial execution ( gulp.series) and the parallel execution ( gulp.parallel) in two ways.
(1) serial (sequential) execution, and in order to perform different gulp3, first began to default task, then execute task1, task2 task order, finally ending default task.

gulp4 if adopted as gulp3 dependent implementation, will be reported Task function must be specified error.

Solution:
use gulp.series('task1','task2') or gulp.parallel('task1','task2') alternatively in gulp3 gulp.task('default', ['task1', 'task2'], function() {... }) manner.
Serial execution ( gulp.series ):

const gulp = require('gulp');

// 定义任务task1
gulp.task('task1', async() => {
  await console.log('task1');
});

// 定义任务task2
gulp.task('task2', async() => {
  await console.log('task2');
});

// 串行执行task1、task2任务
gulp.task('default', gulp.series('task1', 'task2'));
复制代码

The results:

execution order:
Start default => Start Task1 => Finish Task1 => Start Task2 => Finish Task2 => default Finish

(2) are executed in parallel, first began to default task, and then sync to perform parallel tasks, and end default task.

Parallel execution ( gulp.parallel ):

const gulp = require('gulp');

// 定义任务task1
gulp.task('task1', async() => {
  await console.log('task1');
});

// 定义任务task2
gulp.task('task2', async() => {
  await console.log('task2');
});

// 并行执行task1、task2任务
gulp.task('default', gulp.parallel('task1', 'task2'));
复制代码

The results:

execution order:
Start default => Start Task1 => Start Task2 => Finish Task1 => Finish Task2 => default Finish

Important:
1.gulp4 defined tasks employed async await define tasks.
2.gulp4 tasks performed with a serial ( gulp.series) and the parallel execution ( gulp.parallel) mode, can be realized in dependence gulp3 performed by rational serial and parallel configuration.

    Next will explore how to use gulp packed js, css, image, html and how to write gulp in the production and development environment configuration.

5.gulp detected, converted, packaged, compressed js

Requires Plugins:

  • gulp-eslint: eslint detection
  • gulp-babel: babel conversion
  • gulp-concat: the merged file (js / css / html, etc.)
  • gulp-uglify: compressed js

Function:
the current directory main.js, hello.js, world.js eslint for detection, conversion Babel, compressed into app.min.js output to merge directory dist

const gulp = require('gulp');
const babel = require('gulp-babel'); // babel转换
const eslint = require('gulp-eslint'); // eslint检测
const concat = require('gulp-concat'); // 合并文件
const uglify = require('gulp-uglify'); // 压缩js
const del = require('del'); // 清空目录

// 合并压缩的文件
const jsFiles = ['./main.js', './hello.js', './world.js'];

// eslint任务,实现eslint检测和代码格式化
gulp.task('eslint', async() => {
  await gulp.src(jsFiles)
            .pipe(eslint())
            .pipe(eslint.format()) // 格式化
            .pipe(eslint.failAfterError()); // 报错
});

// clean任务,清空dist文件夹
gulp.task('clean', async() => {
  await del(['./dist/']);
});

// jsCompress任务,实现js转换、合并、压缩
gulp.task('jsCompress', async() => {
  await gulp.src(jsFiles)
            .pipe(babel({
              presets: ['@babel/env'] // es6转换为es5
            }))
            .pipe(concat('app.min.js')) // 合并为app.min.js
            .pipe(uglify()) // 文件压缩
            .pipe(gulp.dest('./dist/')) // 文件写入到dist文件夹
});

// 顺序执行clean、eslint、jsCompress任务
gulp.task('default', gulp.series('clean', 'eslint', 'jsCompress'));

复制代码

Perform gulp, task execution success: in dist folder created under the app.min.js
 

6.gulp conversion, combine and compress scss / css

Requires Plugins:

  • gulp-sass: sass compilation
  • gulp-concat: Merge Files
  • gulp-clean-css: css compression

Realize the function:
(. 1) main.scss current directory, style.scss conversion css then combined to write compressed into scss.css dist directory.
(2) all current css file directory is written to the combined compressed into style.min.css dist directory.

const gulp = require('gulp');
const concat = require('gulp-concat'); // 合并文件
const cleanCss = require('gulp-clean-css'); // 压缩css
const sass = require('gulp-sass'); // sass编译
const del = require('del'); // 清空目录

// clean任务,清空dist目录
gulp.task('clean', async() => {
   await del(['./dist']);
});

// sass任务,实现scss文件编译、合并、压缩
gulp.task('sass', async() => {
  await gulp.src(['./main.scss', './style.scss'])
            .pipe(sass()) // sass编译
            .pipe(concat('scss.css')) // 合并为scss.css
            .pipe(cleanCss()) // 压缩css文件
            .pipe(gulp.dest('./dist'));
});

// css任务,实现css合并、压缩
gulp.task('css', async() => {
  await gulp.src(['./*.css'])
            .pipe(concat('style.min.css')) // 合并为style.min.css
            .pipe(cleanCss()) // 压缩
            .pipe(gulp.dest('./dist'));
});

// 先执行clean任务,再并行执行sass和css任务
gulp.task('default', gulp.series('clean', gulp.parallel('sass', 'css')));
复制代码

Perform gulp, task execution success

in dist directory created under the scss.css and style.min.css file.
 

7.gulp compressed html, image

Requires Plugins:

  • gulp-htmlmin: html compression
  • gulp-imagemin: Image Compression

Realize functions:
(1) implement the current html directory to the compressed output under dist directory
(2) to achieve the current heads of the png image output to the dist directory

const gulp = require('gulp');
const htmlmin = require('gulp-htmlmin'); // html压缩
const imagemin = require('gulp-imagemin'); // 图片压缩
const del = require('del'); // 清空目录

// clean任务,清空dist目录
gulp.task('clean', async() => {
  await del('./dist');
});

// html任务,压缩html文件代码
gulp.task('html', async() => {
  await gulp.src('./*.html')
            .pipe(htmlmin({ collapseWhitespace: true })) // 压缩去除空格
            .pipe(gulp.dest('dist'));
});

// image任务,压缩图片
gulp.task('image', async() => {
  await gulp.src('./*.png')
            .pipe(imagemin())
            .pipe(gulp.dest('./dist'));
})

// 先串行执行clean任务,后并行执行html和image任务
gulp.task('default', gulp.series('clean', gulp.parallel('html', 'image')));
复制代码

Perform gulp, the successful implementation of the task

became compressed in dist directory swells html files and image
 

Application 8.gulp in production and development environments

Front-end development process for the development and production environments are often different configuration:
the development environment: from local service, support for debugging, hot update.
Production: compressed merge code for deployment line environment.
Requires Plugins:

  • del: Empty directory
  • gulp-eslint: eslint code detection
  • gulp-babel: babel conversion, into the code es6 es5
  • gulp-concat: Merge Files
  • gulp-uglify: js compression
  • gulp-sass: sass compilation
  • gulp-clean-css: css compression
  • gulp-htmlmin: html compression
  • gulp-imagemin: Image Compression
  • gulp.connect: commissioning services from the server

Implement the functions:
(1) achieve js eslint detection, Babel conversion, combined, compressed
(2) to achieve sass compiling and css combine and compress
(3) implement html compression
(4) achieve image compression
(5) development environment preview, hot update
( 6) the production of individual files packed environment

const gulp = require('gulp');
const babel = require('gulp-babel'); // es6转为es5语法
const eslint = require('gulp-eslint'); // eslint代码检测
const concat = require('gulp-concat'); // 文件合并
const uglify = require('gulp-uglify'); // js压缩
const sass = require('gulp-sass'); // sass编译
const htmlmin = require('gulp-htmlmin'); // html压缩
const connect = require('gulp-connect'); // 起server服务
const imagemin = require('gulp-imagemin'); // 图片压缩
const del = require('del'); // 清空目录
const cleanCss = require('gulp-clean-css'); // css压缩

// 清空dist目录
gulp.task('clean', async() => {
 await del(['./dist']);
});

// html压缩公共函数
const htmlMin = () => {
 return gulp.src('./index.html')
            .pipe(htmlmin(
                 {collapseWhitespace: true}
                 ))
            .pipe(gulp.dest('dist'));
};

// html:dev task,用于开发环境下,浏览器自动刷新
gulp.task('html:dev', async() => {
 await htmlMin().pipe(connect.reload());
});
// html:build task,用于生产环境
gulp.task('html:build', async() => {
 await htmlMin();
});

// sass转换、合并、压缩css公共函数
const cssMin = () => {
 return gulp.src(['./css/style.scss', './css/*.css'])
            .pipe(sass())
            .pipe(concat('style.min.css'))
            .pipe(cleanCss())
            .pipe(gulp.dest('./dist/css'))
};

// css:dev任务,用于开发环境
gulp.task('css:dev', async() => {
 await cssMin().pipe(connect.reload());
});
// css:dev任务,用于生产环境
gulp.task('css:build', async() => {
 await cssMin();
});

// js eslint检测、babel转换、合并、压缩公共函数
const jsMin = () => {
 return gulp.src('./js/*.js')
            .pipe(eslint())
            .pipe(eslint.format())
            .pipe(eslint.failAfterError())
            .pipe(babel({
               presets: ['@babel/env']
             }))
            .pipe(concat('main.min.js'))
            .pipe(uglify())
            .pipe(gulp.dest('./dist/js'));
};

// js:dev任务,用于开发环境
gulp.task('js:dev', async() => {
 await jsMin().pipe(connect.reload());
});
// js:build,用于生产环境
gulp.task('js:build', async() => {
 await jsMin();
});

// 图片压缩公共函数
const imageMin = () => {
 return gulp.src('./img/*.png')
            .pipe(imagemin())
            .pipe(gulp.dest('./dist/img'));
};

// image:dev任务,用于开发环境
gulp.task('image:dev', async() => {
 await imageMin().pipe(connect.reload());
});
// image:build任务,用于生产环境
gulp.task('image:build', async() => {
 await imageMin();
});

// server任务,目录为dist,入口文件为dist/index.html,port 8080
gulp.task('server', () => {
  connect.server(
   {
     root: './dist',
     port: 8080,
     livereload: true
   }
 )
});

// watch任务,监听源文件变化,执行对应开发任务
gulp.task('watch', () => {
 gulp.watch(['./css/*.css', './css/*.scss'], gulp.series('css:dev'));
 gulp.watch('./js/*.js', gulp.series('js:dev'));
 gulp.watch('./index.html', gulp.series('html:dev'));
 gulp.watch('./img/*.png', gulp.series('image:dev'));
});

// dev任务,启动开发环境
gulp.task('dev', gulp.series(gulp.parallel('watch', 'server')));

// build任务,用于生产环境下打包压缩源代码
gulp.task('build', gulp.series('clean', gulp.parallel('html:build', 'js:build', 'css:build', 'image:build')))
复制代码

In the current directory package.json the script to add dev and build command:

"scripts": {
   "dev": "gulp dev",
   "build": "gulp build"
 },
复制代码

Execution npm run dev, you can start the development mode, when we modify the source html, css, js and other documents, will perform the corresponding task repackaged package, the browser automatically refreshed.


Performing npm run build, in the source code directory packing.
Html contains the packing process, css, js, image and other resources in the dist folder.
 

    These are the bloggers explore the application of gulp4 of the front-end engineering. After reading the article I believe we should have a preliminary understanding gulp, little follow-interested partners can also consider gulp integrated into webpack configuration, to better enhance the development efficiency.

Source Address

gulp Chinese network: www.gulpjs.com.cn

(Think nice little partner can give a point like this article, as well as github star look, gray often thanks ^ _ ^)

Reproduced in: https: //juejin.im/post/5ce92417f265da1ba328a0e0

Guess you like

Origin blog.csdn.net/weixin_33813128/article/details/91444400