preface

The blogger was recently preparing to develop a UI component library and ran into a problem. The blogger wanted to package component style SCSS files separately, rather than webpack them with components. The investigation found that GULP could solve this problem, so the application of GULP4 in front-end engineering was studied.

1. Introduction

Gulp is a stream-based automated build tool that reads and writes data based on streams in nodeJs, which is faster than Grunt’s direct IO reading and writing of files. With gulp, you can automatically test, check, merge, compress, format js/sass/less/ CSS files, and listen for the files to repeat the specified steps after changes. The biggest difference between Gulp and Webpack is that gulp does not pack non-JS resources like CSS /less/image in a modular manner. Gulp is applicable to pack sASS, less, and CSS separately, compress images, and compress HTML.

2. Install gulp

Install gulp globally

$ npm install gulp -g


$ npm install gulp –save-dev


$ gulp -v

CLI version: 2.2.0

The Local version: 4.0.2


// Define default task(gulp4) gulp.task('default', async() => { 
    await ...
});
Copy the code

Execute gulp (default task is executed by default)

$ gulp

3. Commonly used API

  • Gulp.src (globs[, options]) reads the files in the directory
  • Gulp.dest (path[, options]) writes files to the directory
  • Gulp.task (name[, deps], fn) defines a gulp task
  • Gulp.pipe () processes the object file through the plug-in
  • Gulp.watch (glob [, opts], Tasks) or gulp.watch(glob [, OPts, CB]) monitors the file system and can perform operations when files are changed
  • Gulp. Series (task1, task2, task3
  • Gulp. Parallel (task1, task2, task3) (gulp4 added

4. Gulp3 glup4

The changes of GULp3 and GULP4 are mainly reflected in the changes of task definition and execution system.

4.1 Task definition and execution sequence in GULp3

Gulp3 A task is executed only after the dependent tasks of the task are executed in sequence.

Task definition in gulp3:

// gulpfile.js const gulp = require('gulp'); // Define task gulp.task('task1'.function() {
  console.log('task1'); }); // Define task gulp.task('task2'.function() {
  console.log('task2'); }); // Define a default task that depends on task1 and task2 gulp.task('default'['task1'.'task2'].function() {
  console.log('done');
});
Copy the code

Task execution in gulp3:



Order of execution:

start task1 => finish task1 => start task2 => finish task2 => start default => finish default

4.2 Task definition and execution sequence in GULP4

Task definitions and dependent execution modes in GULp3 are no longer supported in GULp4. Suppose the definition task still uses gulp3:

gulp.task('task1'.function() {
  console.log('task1');
});
Copy the code

Did you forget to signal async completion?



Workaround: define tasks with async await

// Define task gulp.task('task1', async() => {
  await console.log('task1');
});
Copy the code

Run task1. The task is successfully executed.



In GULP 4, tasks are executed in serial execution (gulp. Series) and parallel execution (gulp. Parallel) instead of dependent execution. (1) Serial execution, different from the sequential execution in Gulp3, starts the default task first, then executes task1 and task2 tasks sequentially, and finally ends the default task.










gulp.series('task1','task2')
gulp.parallel('task1','task2')
gulp.task('default', ['task1', 'task2'], function() {... })



gulp.series

const gulp = require('gulp'); // Define the task task1 gulp.task('task1', async() => {
  await console.log('task1'); }); // Define the task task2 gulp.task('task2', async() => {
  await console.log('task2'); }); // Execute task gulp. Task ('default', gulp.series('task1'.'task2'));
Copy the code

Execution Result:



Order of execution:

start default => start task1 => finish task1 => start task2 => finish task2 => finish default

(2) Parallel execution: start the default task, then synchronously execute the parallel task, and finally end the default task.

gulp.parallel

const gulp = require('gulp'); // Define the task task1 gulp.task('task1', async() => {
  await console.log('task1'); }); // Define the task task2 gulp.task('task2', async() => {
  await console.log('task2'); }); // Execute task gulp.task('default', gulp.parallel('task1'.'task2'));
Copy the code

Execution Result:



Order of execution:

start default => start task1 => start task2 => finish task1 => finish task2 => finish default

1. Tasks defined in gulp4 are defined in async await mode. 2. There are serial (gulp.series) and parallel (gulp.parallel) execution modes in GULp4, and the dependent execution in GULp3 can be realized through reasonable configuration of serial and parallel.

Next, we’ll explore how to use gulp to package JS, CSS, image, HTML, and how to write gulp configurations in production and development environments.

5. Gulp detects, converts, packages and compresses JS

Required plug-ins:

  • Gulp-eslint: esLint checks
  • Gulp-babel: Babel conversion
  • Gulp-concat: Merge files (JS/CSS/HTML etc.)
  • Gulp-uglify: compressed JS

Implementation functions: EsLint detection of main.js, hello.js and world.js in the current directory, Babel conversion, consolidation and compression into app.min.js output to dist directory

const gulp = require('gulp');
const babel = require('gulp-babel'); // Babel const eslint = require('gulp-eslint'); // eslint checks const concat = require('gulp-concat'); // merge file const uglify = require('gulp-uglify'); // compress js const del = require('del'); // Empty directory // merge compressed file const jsFiles = ['./main.js'.'./hello.js'.'./world.js']; // EsLint task that implements esLint detection and code formatting gulp.task('eslint', async() => {await gulp.src(jsFiles).pipe(eslint()).pipe(eslint.format()) // format.pipe (eslint.failafterError ()); / / error}); // Clean the dist folder gulp.task('clean', async() => {
  await del(['./dist/']); }); // The jsCompress task implements js conversion, merging, and compressing gulp.task('jsCompress', async() => {
  await gulp.src(jsFiles)
            .pipe(babel({
              presets: ['@babel/env'}). Pipe (concat().'app.min.js'Pipe (uglify()) // File compression.pipe(gulp.dest())'./dist/') // Write files to dist folder}); // Execute clean, eslint, jsCompress tasks gulp.task('default', gulp.series('clean'.'eslint'.'jsCompress'));

Copy the code

Gulp is executed successfully.App.min.js is generated under the dist folder

 

Gulp converts, merges and compresses SCSS/CSS

Required plug-ins:

  • Gulp-sass: sass compilation
  • Gulp-concat: merges files
  • Gulp-clean-css: compresses the CSS

(1) The current directory main. SCSS, style. SCSS convert CSS and then merge and compress into SCs. CSS and write to dist directory. (2) All CSS files in the current directory are merged and compressed into style.min. CSS and written to dist directory.

const gulp = require('gulp');
const concat = require('gulp-concat'); // merge file const cleanCss = require('gulp-clean-css'); // compress CSS const sass = require('gulp-sass'); // sass const del = require('del'); Gulp.task (dist gulp.task(dist gulp.task)'clean', async() => {
   await del(['./dist']); }); Gulp. Task (// sass)'sass', async() => {
  await gulp.src(['./main.scss'.'./style.scss'].pipe(sass()) // sass compiles.pipe(concat())'scss.css')) // merge into scs.css.pipe (cleanCss()) // compress the CSS file.pipe(gulp.dest()'./dist')); }); Gulp. Task ('css', async() => {
  await gulp.src(['./*.css'])
            .pipe(concat('style.min.css')) // merge to style.min.css.pipe (cleanCss()) // compress.pipe(gulp.dest()'./dist')); }); // Execute the clean task first, then execute the sass and CSS task gulp.task('default', gulp.series('clean', gulp.parallel('sass'.'css')));
Copy the code

The gulp command is executed successfully



CSS and style.min. CSS files are generated in the dist directory.

 

7. Gulp compresses HTML and image

Required plug-ins:

  • Gulp-htmlmin: HTML compression
  • Gulp-imagemin: image compression

Implementation functions: (1) to achieve the output of HTML compression under the current directory to dist directory (2) to achieve the output of PNG images under the current directory to dist directory

const gulp = require('gulp');
const htmlmin = require('gulp-htmlmin'); // HTML compression const imagemin = require('gulp-imagemin'); Const del = require(const del = require('del'); Gulp.task (dist gulp.task(dist gulp.task)'clean', async() => {
  await del('./dist'); }); Gulp.task ('html', async() => {
  await gulp.src('./*.html')
            .pipe(htmlmin({ collapseWhitespace: true})) // zip to remove whitespace. Pipe (gulp.dest()'dist')); }); Gulp. Task ('image', async() => {
  await gulp.src('./*.png')
            .pipe(imagemin())
            .pipe(gulp.dest('./dist')); }) // Execute gulp. Task (gulp.'default', gulp.series('clean', gulp.parallel('html'.'image')));
Copy the code

The gulp command is executed successfully



Generate compressed HTML files and images in the dist directory

 

8. Application of GULP in production and development environment

Front-end development process, for the development environment and production environment configuration is often different: development environment: local services, support debugging, hot update. Production environment: Compress merge code for deployment line environment. Required plug-ins:

  • Del: Clears the directory
  • Gulp-eslint: esLint code checks
  • Gulp-babel: Babel conversion to convert ES6 code to ES5
  • Gulp-concat: merges files
  • Gulp-uglify: JS compression
  • Gulp-sass: sass compilation
  • Gulp-clean-css: indicates CSS compression
  • Gulp-htmlmin: HTML compression
  • Gulp-imagemin: image compression
  • Gulp. connect: Start server service debugging

Implementation functions: (1) js ESLint detection, Babel conversion, merge, compression (2) sASS compilation and CSS merge, compression (3) HTML compression (4) image compression (5) development environment preview, hot update (6) production environment each file packaging

const gulp = require('gulp');
const babel = require('gulp-babel'); // es6 to es5 syntax const eslint = require('gulp-eslint'); // esLint code checks const concat = require('gulp-concat'); // file merge const uglify = require('gulp-uglify'); // const sass = require('gulp-sass'); // sass compile const htmlmin = require('gulp-htmlmin'); // HTML compression const connect = require('gulp-connect'); // Start server const imagemin = require('gulp-imagemin'); Const del = require(const del = require('del'); // clear the directory const cleanCss = require('gulp-clean-css'); Gulp.task ()'clean', async() => {
 await del(['./dist']); }); // HTML compression public function const htmlMin= () = > {return gulp.src('./index.html')
            .pipe(htmlmin(
                 {collapseWhitespace: true}
                 ))
            .pipe(gulp.dest('dist')); }; // HTML :dev task, used in the development environment, the browser automatically refresh gulp.task('html:dev', async() => {
 await htmlMin().pipe(connect.reload()); }); // HTML :build task for production environment gulp.task('html:build', async() => {
 await htmlMin(a); }); // sass transforms, merges, and compresses CSS public functions 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 task for development environment gulp.task('css:dev', async() => {
 await cssMin().pipe(connect.reload()); }); // CSS :dev task for production environment gulp.task('css:build', async() => {
 await cssMin(a); }); // js esLint detects, transforms, merges, and compresses public functions 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 task for development environment gulp.task('js:dev', async() => {
 await jsMin().pipe(connect.reload()); }); // js:build for production environment gulp.task('js:build', async() => {
 await jsMin(a); }); // Image compression public function const imageMin= () = > {return gulp.src('./img/*.png')
            .pipe(imagemin())
            .pipe(gulp.dest('./dist/img')); }; // image:dev task for development environment gulp.task('image:dev', async() => {
 await imageMin().pipe(connect.reload()); }); // image:build task for production environment gulp.task('image:build', async() => {
 await imageMin(a); }); Dist /index.html, port 8080 gulp.task(dist/index.html)'server', () => {
  connect.server(
   {
     root: './dist',
     port: 8080,
     livereload: true})}); Gulp. Task (gulp.'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 task to start the development environment gulp.task('dev', gulp.series(gulp.parallel('watch'.'server'))); Gulp.task (// build task for packaging compressed source code in production environment'build', gulp.series('clean', gulp.parallel('html:build'.'js:build'.'css:build'.'image:build')))
Copy the code

Add dev and build commands to script in package.json in the current directory:

"scripts": {
   "dev": "gulp dev"."build": "gulp build"
 },
Copy the code

performnpm run dev, can start the development mode, when we modify the source HTML, CSS, JS and other files, the corresponding packaging task will be performed to repackage, the browser automatically refresh.





performnpm run buildPackage the source code in the directory.

The dist folder contains the packaged HTML, CSS, JS, image and other resources.

 

Above is the application of gulP4 in front-end engineering explored by the blogger. After reading this article, you should have a preliminary understanding of gulp. If you are interested, you can also consider integrating GULp into webPack configuration to improve development efficiency.

Source code address

Gulp Chinese website: www.gulpjs.com.cn

(If you think it’s great, please give it a thumbs up and give it a github star. Thank you.)