preface

Although Webpack is now very powerful, gulp has not completely retired from the stage of history, sometimes interview will ask whether you use gulp, if you have encountered gulp related, I hope this article will help you!

Usually learn the language finch address

www.yuque.com/kongdesheng…

What is GULP?

Gulp.js is an automated build tool designed to automate the time-consuming and repetitive tasks involved in Web development. Gulp.js is built on Node.js, and you can quickly build projects using the power of Node.js streams.

The advantages of gulp

  • Code over configuration, Node best practices, a streamlined set of apis, and Gulp makes life easier than ever.
  • Based on Node’s powerful stream capabilities, gulp speeds up builds by not writing files to disk immediately.
  • Strict guidelines are followed to ensure that our plug-ins are simple in structure and run with controllable results.

The disadvantage of gulp

Plugin bugs are difficult to deal with.

The preparatory work

Step1. Check the environment configuration

Let’s first check that Node, NPM or NPX or YARN is properly installed.

New Node and NPM users may encounter permissions issues. These problems are displayed as errors in EACCESS during installation. If this happens, refer to the NPM guide to fix permissions.

Step2. Install the gulp command-line tool

Install command

npm install --global gulp-cli
Copy the code

Step3. Create a project directory

Here we will create a project called KDS-gulp as an example.

Step4. Initialize package.json

CD go to our project directory (kds-gulp) and run the following command to create package.json file, in this case using yarn

// The NPM command can also be used to yarn initCopy the code

Step5. Install gulp development dependencies

Install command

yarn add --save-dev gulp
Copy the code

Step6. Check the version

Execute the command to check that we have successfully installed the plug-in

gulp -v
Copy the code

Step7. Establish gulpfile.js file

Gulp also requires a file as its entry file. In gulp this file is called gulpfile.js.

Step8. Prepare project resources

Create a new SRC file under the project path and put the development files and static resources we need into it. Here are the static resources I prepared, and I’ll explain in detail how each type of file can be automated using gulp.

If you want to try it out for yourself, just prepare your own resource file with the file suffix.

└ ─ ─ KDS - gulp · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · project root ├ ─ public · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · the static Folder │ └ ─ the favicon. Ico · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · the static file (unprocessed) ├ ─ the SRC · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · the source folder │ ├ ─ assets · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · assets Folder │ │ ├ ─ fonts · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · fonts folder │ │ │ └ ─ pages. The vera.ttf · · · · · · · · · · · · · · · · · · · · · · · · · · · · · The font file (imagemin) │ │ ├ ─ images · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · images folder │ │ │ └ ─ logo. The PNG · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · image file (imagemin) │ │ ├ ─ scripts · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · scripts folder │ │ │ └ ─ main. Js · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · script file (Babel/uglify) │ │ └ ─ styles · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · styles folder │ │ ├ ─ _variables. SCSS · · · · · · · · · · · · · · · · · · · · · · · partial sass file (dont Output) │ │ └ ─ main. SCSS · · · · · · · · · · · · · · · · · · · · · · · · · · · · · entry SCSS file (SCSS/postcss) │ ├ ─ layouts · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · layouts folder │ │ └ ─. Basic HTML · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · layout file (dont Output) │ ├ ─ partials · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · partials folder │ │ └ ─ header. The HTML · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · partial file (dont output) │ ├ ─ the about the HTML · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · page file (use the layout & partials) │ └ ─ index. The HTML · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · page file (use layout & partials) ├ ─ . Csscomb. Json · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · csscomb config file ├ ─. Editorconfig · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · Editor config file ├ ─. Gitignore · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · git ignore file ├ ─. Travis. Yml · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · Travis ci config file ├ ─ CHANGELOG. Md · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · repo Changelog ├ ─ LICENSE · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · repo LICENSE ├ ─ the README, md · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · repo readme ├ ─ gulpfile. Js · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · gulp the tasks of the file ├ ─ package. Json · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · package file └ ─ yarn. The lock · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · yarn lock fileCopy the code

To get started

Our logical code for processing resource files needs to be uninstalled in gulpfile.js

Step1. Install gulp-load-plugins

After installing this module to keep the code simple, we need to require many plugins (if you don’t know what gulp-load-plugins do, look for common plugins).

Install command

yarn add gulp-load-plugins --dev
Copy the code

Step2. Style compilation

Look at the project directory for project KDS-gulp. SCSS style files exist at SRC /assests/styles, but the production environment does not recognize these style files and we need to convert them to recognizable CSS files.

  • Install the gulp-sass plugin.
  • Note: SCSS files starting with _ are ignored and will not be converted.
  • Output the translated files to the temp temporary directory for later merging operations.
  • Run the gulp style test.

Installation command:

yarn add gulp-sass --dev
Copy the code

Write the code block in gulpfile.js: Add {base: ‘SRC ‘} if you want to preserve the file hierarchy of the input directory in the output directory

const style = () =>{
    return src('src/assets/styles/*.scss',{base: 'src'})
    .pipe(plugins.sass())
    .pipe(dest('temp'))
}
module.exports = {
    style
}
Copy the code

Step3. Script editing

There are js scripts in the SRC /assests/scripts directory of the kDS-gulp project. The es6 syntax may be used in actual development, but there may be some compatibility problems with ES6 in production environment. We need to convert ES6 syntax to ES5 syntax through Babel.

  • Install the gulp-babel plug-in.
  • Write the conversion function.
  • Output the translated files to the temp temporary directory for later merging operations.
  • Run gulp Scripts tests.

Installation command:

yarn add gulp-babel --dev
Copy the code

Write code:

const scripts = () =>{ return src('src/assets/scripts/*.js',{base: 'src'}) .pipe(plugins.babel({presets: ['@babel/env']}).pipe(dest('temp'))} // module.exports = {scripts}Copy the code

Step5. Resource file processing

Now start to compress and cache our static resources such as images and fonts.

  • Install gulp-imagemin and gulp-cache.
  • Compress images to reduce image size.
  • Because image compression is time-consuming, we only need to compress the modified image, and the unmodified image is directly read from the cache.
  • Write the conversion function.
  • Run gulp img and gulp font tests.

Install command

yarn add gulp-cache --dev
yarn add gulp-imagemin --dev
Copy the code

Write the code

const img = () =>{ return src('src/assets/images/**',{base: 'SRC '}).pipe(plugins.cache(plugins.imagemin({progressive: true,// whether to incrementalize svgoPlugins: [{removeViewBox:false}],// SvGO plugin whether to remove slide laced: true // Whether to line scan})). Pipe (dest('dist')} module.exports = {img}Copy the code

The same goes for font style files

const font = () => {
    return src('src/assets/fonts/**',{base: 'src'})
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}
module.exports = {
    font
}
Copy the code

Step6. Additional files

Other related files that are not SRC also need to be packaged under dist, such as public directory, which also needs to be dealt with.

const extra = () =>{
    return src('public/**',{base: 'public'})
    .pipe(dest('dist'))
}
module.exports = {
    extra
}
Copy the code

Step7. Execute commands in combination

If we one by one to knock command execution conversion operations, trouble and trival, using the parallel (), the series () are combined to nested, parallel and series can go to a website API view, there is not much to do.

  • Use parallel(),series() to group functions together.
  • Before generating dist, execute clean to clean it to prevent caching.
  • The files in temp directory are merged and compressed to the dist directory.
  • To learn about the merge compression process, skip to the section preparing to go live.
  • Run the gulp build test.
Const clean = () =>{return SRC (['dist','temp']).pipe(plugins.clean())} const compile = parallel([style,scripts,page]); Const build = series(clean, parallel(series(complie, useref),extra, image, font)) Exports = {build} step1,2,3,4,5,6Copy the code

Testing and debugging

During development we need to constantly modify the code and display it in the browser for debugging and development, and we want this to be “hot update”. We can use gulp to create a server to meet our development needs.

Step1. Create the base server

  • Install the browser-sync module.
  • Create a server using browser-sync’s Create section.
  • Write our serve function and initialize our server.
  • After gulp build, perform gulp serve test.

Install command

yarn add browser-sync --dev
Copy the code

Creating a Server

Const borwserSync = require('browser-sync') const bs = borwsersync.create ()// Open browser const serve = () => {bs.init({ File :'dist/**',// Refresh the dist file when there are changes in the dist file server: {baseDir: ['dist',' SRC ','public'],// Routes: {'/node_modules': 'node_modules' // automatically maps to node_modules}})}Copy the code

Step2. Listen for file changes

This can be done dynamically with new servers, but only when the dist directory is changed, so we have to do the build operation again and again, which is very troublesome, so we need to simplify this operation.

  • Watch () listens for file changes to dynamically execute our corresponding methods.
  • Merge command lines.
  • Execute the gulp Develop test.
const serve = () => {... // The first argument is the listening path, and the second argument is the corresponding handler. watch('src/assets/styles/*.scss', style) watch('src/assets/scripts/*.js', script) watch('src/*.html', page) watch([ 'src/assets/images/**', 'src/assets/fonts/**', 'public/**' ], bs.reload) } const compile = parallel([style,scripts,page]); Const develop = series(compile,serve) module.exports = {compile, develop} const develop = series(compile,serve) module.exports = {compile, develop}Copy the code

Online preparation

We need to merge the HTML files before we go live. We’re going to use useref here.

Step1. Merger

  • Gulp-useref consolidates HTML references to multiple CSS and JS files, reducing the number of dependent files and thus reducing the number of browser requests.
  • Gulp-useref consolidates all files in a block of HTML based on comments that need to be consolidated and compressed.
  • It only merges, not compresses!

Install command

yarn add gulp-useref --dev
Copy the code

Write the code

const useref = {
    rerurn src('temp/*.html',{base: 'temp'}).pipe(plugins.useref({searchPath:['temp','.'] }))  
           .pipe(dest('dist')) 
}
Copy the code

Step2. Compression

  • We need to compress JS, CSS and HTML.
  • Install gulp-uglify, gulp-htmlmin, gulp-clean-CSS modules
  • Use the if plug-in to determine the current environment and perform different compression.

Install command

yarn add gulp-htmlmin --dev
yarn add gulp-uglify --dev
yarn add gulp-clean-css --dev
yarn add gulp-if --dev
Copy the code

Write the code

const useref = { rerurn src('temp/*.html',{base: 'temp'}).pipe(plugins.useref({searchPath:['temp','.'] })) .pipe(plugins.if(/\.js$/, plugins.uglify())) .pipe(plugins.if(/\.css$/, plugins.cleanCss())) .pipe(plugins.if(/\.html$/, Htmlmin ({collapseWhitespace: true, minifyCSS: true, // Style and javascript in the page collapse minifyJS: true }))) //html .pipe(dest('dist')) }Copy the code

Common plug-in

The gulp plugin library is very rich. If you need it, you can check it on the official website. gulpjs.com/plugins/

gulp-babel

Description: Compile ES6 code into ES5.

const gulp = require('gulp');
const babel = require('gulp-babel');
gulp.src('./js/index.js')
    .pipe(babel({
        presets: ['@babel/preset-env']
}))
    .pipe(gulp.dest('./dist'))
Copy the code

gulp-sass

Description: Compile sass.

const sass = require('gulp-sass'); gulp.src('./sass/**/*.scss') .pipe(sass({ outputStyle: }). Pipe (gulp.dest('./dist/ CSS '));Copy the code

gulp-rename

Description: Used to rename a file in a file stream.

var rename = require("gulp-rename"); Gulp. SRC ('. / hello. TXT '), pipe (rename (' gb/goodbye. Md)) / / directly to modify the file name and path. The pipe (gulp. Dest ('. / dist ')); Gulp.src ('./hello.txt'). Pipe (rename({dirname: "text", // basename: "goodbye", // prefix: "Pre -" prefix/suffix: "- min", / / suffix extname: "HTML" / / extensions})) pipe (gulp. Dest ('. / dist '));Copy the code

gulp-load-plugins

  • To use the gulp plugin, first use require to load the plugin in.
  • If you load a lot, the code gets long and stinky.
  • The gulp-load-plugins plug-in is designed to solve this problem.
Var gulp = require('gulp'), // gulp = require('gulp-a'), b = require('gulp-b') C = the require (' gulp - c), d = the require (' gulp - d '), / / more plug-ins... z = require('gulp-... '); // package.json "devDependencies": {"gulp": "^3.9.1", "gulp-concat": "^2.6.1", "gulp-rename": Gulp-uglify: "^2.0.1"} // gulpfile.js var plugins = require('gulp-load-plugins')(); / / $is an object, loading the plug-in in the dependent on gulp. SRC ('. / / * * *. Js'), pipe (plugins. Concat (' all. Js')) / / use plug-ins can use $. PluginsName () .pipe(plugins.uglify()) .pipe(plugins.rename('all.min.js')) .pipe(gulp.dest('./dist'))Copy the code

gulp-clean-css

Description: Compress the CSS file to reduce the file size.

const gulp = require('gulp');
const babel = require('gulp-babel');

gulp.src('./js/index.js')
    .pipe(babel({
        presets: ['@babel/preset-env']
    }))
    .pipe(gulp.dest('./dist'))
Copy the code

gulp-cache

  • Monitor that the image has been changed, replaced, and then compress.
  • If only the name of the image is changed, it will not be replaced.
var cache = require('gulp-cache'); gulp.task('img', function ( ){ gulp.src('./src/images/*.{jpg|jpeg|png|gif}',) .pipe( cache( imagemin({ progressive : True,// Whether to incrementally optimize svgoPlugins: [{removeViewBox:false}],// Whether the SvGO plug-in removes the lace slide: Whether true / / all scanning}))) pipe (gulp. Dest ('. / SRC/images / *. {JPG | jpeg | PNG | GIF} '))});Copy the code

gulp-swig

Swig is a simple, powerful and extensible JavaScript template engine.

var swig = require('gulp-swig');
var opts = {
  data: {
    headline: "Welcome"
  }
};
gulp.task('templates', function() {
  gulp.src('./lib/*.html')
    .pipe(swig(opts))
    .pipe(gulp.dest('./dist/'))
});
Copy the code

gulp-imagemin

Description: Compressed image.

var imagemin = require('gulp-imagemin');

gulp.src('./img/*.{jpg,png,gif,ico}')
    .pipe(imagemin())
    .pipe(gulp.dest('./dist/img'))
Copy the code

gulp-useref

Description: Merge files.

var gulp = require('gulp'),
    useref = require('gulp-useref');

gulp.task('default', function () {
    return gulp.src('app/*.html')
        .pipe(useref())
        .pipe(gulp.dest('dist'));
});
Copy the code

In the HTML

Need to work with build comments using < HTML > <head> <! -- build:css css/combined.css --> <link href="css/one.css" rel="stylesheet"> <link href="css/two.css" rel="stylesheet"> <! -- endbuild --> </head> <body> <! -- build:js scripts/combined.js --> <script type="text/javascript" src="scripts/one.js"></script> <script type="text/javascript" src="scripts/two.js"></script> <! -- endbuild --> </body> </html>Copy the code

gulp-uglify

Uglify engine is used to compress JS files.

var gulp = require('gulp'), uglify = require("gulp-uglify"); Gulp.task ('minify-js', function () {gulp.src('js/*.js') // the js file to compress.pipe(uglify()) // Use uglify to compress.  .pipe(gulp.dest('dist/js')); // compressed path});Copy the code

gulp-minify-css

Description: You can use this plug-in to compress CSS files.

var gulp = require('gulp'), minifyCss = require("gulp-minify-css"); gulp.task('minify-css', Function () {gulp.src(' CSS /*.css').pipe(minifyCss()) // zip css.pipe (gulp.dest('dist/ CSS ')); });Copy the code

gulp-htmlmin

Description: Used to compress HTML files.

var gulp = require('gulp'), minifyHtml = require("gulp-htmlmin"); gulp.task('minify-html', Function () {gulp.src(' HTML /*.html').pipe(minifyHtml()).pipe(gulp.dest('dist/ HTML ')); });Copy the code