concept

The front-end construction tools are Grunt, Gulp and Webpack. Grunt is relatively old, with few functions, updates and plug-ins.

Gulp is an automated build tool designed to automatically process static resources. Simply put, GULP is used to package projects.

Gulp is a task-based tool, that is, gulp specifies that no matter what function is done, it must be managed by a unified interface. You must register a task, and then perform the task. In the task code, you must do the desired function. This is one of the characteristics of GULP: task-based.

Liverpoolfc.tv: gulpjs.com/

Chinese document: www.gulpjs.com.cn/docs/

How to use the plug-in: www.npmjs.com

The installation

Install gulp globally

cnpm i gulp -g  
Copy the code

Check whether the installation is successful

gulp -v  

#The version information is displayed after the installation is successful
Copy the code

Initialize the project

cnpm init -y 

#A package.json file is generated upon success
#Note: this command cannot be used in a Chinese directory, so use NPM init instead
Copy the code

Install gulp locally in your project

When using CNPM, the default download will not be recorded in package.json file

cnpm i gulp --seve-dev
#shorthand
cnpm i gulp -D
Copy the code
At the back of the other parameters, seve | - S#It is forced to be saved in package.json, which means the project depends on it. I need him to write code during the development, and after the project goes online, he is also needed for the project to run

--save-dev | -D 
#Pageckage.json is mandatory, which means I need it when I'm developing, like a package tool, and then when the project goes live, I don't need it to run the project
Copy the code

In the future, using CNPM I in a server environment will install project dependencies, but not development dependencies

Introduction to use

Create the glupfile.js file

Create a glupfile.js file in the root directory of the project. The file name is fixed and cannot be changed

Each function of gulp is a task, a task of compressing CSS, a task of merging files. Gulp specifies that tasks be written in a file called glupfile.js, which is used to configure all tasks.

Write the code

Write the following code in glupfile.js

function defaltTask(cb) {
    console.log("Test successful");
    cb()
}

exports.default = defaltTask;
Copy the code

Perform this task on the command line

gulp
Copy the code

Now that our basic introductory test is over, let’s take a look at some of the commonly used GULp apis for the rest of our study

Gulp several common interfaces

  • Series: Synchronization task

  • Parallel: asynchronous task

  • SRC: reads the file

  • Dest: Writes files

  • Watch: Monitors file changes

  • Pipe, pipe

The series, Parallel, SRC, Dest, watch apis are all derived from gulp

let {series,parallel,src,dest,watch} = require('gulp');
Copy the code

Synchronization task

If you want multiple tasks to execute sequentially, you need to use gulp’s Series interface to execute tasks synchronously

// Export the tasks and execute them in the ordered order
exports.default = series(print1, print2)
Copy the code

Asynchronous tasks

If you want two tasks to be executed asynchronously, you need to use gulp’s Parallel interface to execute tasks asynchronously

// Export the tasks and execute them in the ordered order
exports.default = parallel(print1, print2)
Copy the code

Read the file

To read a local file into gulp memory, you need to use the GULp SRC interface to read the data stream

SRC (path of the file to read)Copy the code

Written to the file

To export the in-memory data to a local file, you need to use the dest interface of gulp. The parameter is a folder path

Dest (folder path for output files)Copy the code

The pipe

Take the data stream over and manipulate it without deconstructing it

Since all gulp operations are stream-based, we need to stream the results of the previous step to the next operation, using pipes in between:

Previous action.pipe(next action)Copy the code

Monitor file changes

Used to monitor changes in one or more files. You can perform a task function or a combination of tasks when changes occur

Watch (monitor file or array of files, [options], [task])Copy the code

Gulp plug-in

We need to deal with file merge, compression and other operations, which are not provided in the interface, are put in the plug-in

#Download plug-ins:NPM install plugin name --save-devCopy the code
  • Gulp-concat: Merge files (JS/CSS)

  • Gulp-uglify: compresses JS files

  • Gulp-rename: renames a file

  • Gulp-less: compiles less

  • Gulp-sass: compiles sass

  • Gulp-clean-css: compresses the CSS

  • Gulp-htmlmin: compresses HTML files

  • Gulp-load-plugins: package plug-ins

  • Gulp-autoprefixer: prefixes the CSS

  • Turn ES6 ES5

  • Gulp-clean: Clears the destination folder

  • Gulp-webserver: Starts a server

  • Gulp-connect: hot load, configure a server

  • Open: Automatically opens the browser

  • Gulp-imagemin: Compressed image

  • Gulp-file-include: gulp package component

Multiple plug-ins are downloaded in the project

cnpm i gulp-concat gulp-uglify gulp-rename gulp-sass gulp-clean-css gulp-htmlmin gulp-webserver gulp-load-plugins Gulp-autoprefixer [email protected] babel-core babel-preset- ES2015 gulp-clean -dCopy the code

Fully automated build projects

This project uses most of the plug-ins that can be used, and some plug-ins are not used. If there are requirements of other plug-ins in the project, you can go to www.npmjs.com to search for the use of relevant plug-ins

The directory structure

Gulpfile. Js code

// Fully automated build projects
const { src, dest, parallel, series, watch } = require("gulp");
const _ = require("gulp-load-plugins") ();// Define HTML tasks
function handlerHtml(cb) {
    src('./src/*.html')
        .pipe(_.fileInclude({ // Import the corresponding HTML fragment according to the configuration
            prefix: '@ @'.// A custom identifier
            basepath: './src/components'   // Base directory, the directory where component files reside
        }))
        .pipe(_.htmlmin({ collapseWhitespace: true })) // True removes Spaces and newlines
        .pipe(dest('./dist/'))
    cb();
}
// Define CSS tasks
function handlerCss(cb) {
    src('./src/assets/sass/*.scss')
        .pipe(_.sass())     // Convert sass files to CSS files
        .pipe(_.autoprefixer()) // Prefix CSS in package.json
        .pipe(_.cleanCss()) // Compress the CSS file
        .pipe(_.rename({ extname: ".min.css" }))  // Rename the file
        .pipe(dest('./dist/css/'))
    cb();
}
// Define js tasks
function handlerJs(cb) {
    src('./src/assets/js/*.js')
        .pipe(_.babel({ presets: ['es2015']}))// Convert the syntax above ES6 to ES5 syntax
        .pipe(_.uglify())   // Compress the js
        .pipe(_.rename({ extname: ".min.js" })) // Rename the file
        .pipe(dest('./dist/js/'))
    cb();
}

// Define compressed images and fonts
function handlerImg(cb) {
    src('./src/assets/image/*.*')
        .pipe(_.imagemin())
        .pipe(dest('./dist/img'))
    cb()
}

// Define a task to listen for file changes
function listenerFile(cb) {
    watch(['./src/*.html'.'./src/components/*.html'] and {ignoreInitial: false }, handlerHtml);
    watch('./src/assets/sass/*.scss', { ignoreInitial: false }, handlerCss);
    watch('./src/assets/js/*.js', { ignoreInitial: false }, handlerJs);
    cb();
}

// Create a server
function server(cb) {
    src('./dist', { allowEmpty: true })
        .pipe(_.webserver({
            livereload: true.// Whether to refresh automatically
            host: "localhost".// Set the domain name
            port: 8888.// Set the port
            open: true.// Automatically open the viewer
            fallback: "index.html".// Open the page by default
            proxies: [  // Configure the proxy
                {
                    source: '/runoob'.// Custom address - newbie
                    target: 'https://www.runoob.com/' // The destination address of the proxy
                },
                {
                    source: '/baidu'.// Custom address - Baidu
                    target: 'https://www.baidu.com/' // The destination address of the proxy
                }
            ]
        }))

    cb();
}
// Export tasks
exports.default = series(parallel(handlerHtml, handlerCss, handlerJs, handlerImg), listenerFile, server);
Copy the code

Package. The json code

{
  "name": ""."version": "1.0.0"."description": ""."main": "index.js"."dependencies": {},
  "devDependencies": {	// Development dependency, please remove the comment in the project
    "babel-core": "^ 6.26.3"."babel-preset-es2015": "^ 6.24.1"."gulp": "^ 4.0.2." "."gulp-autoprefixer": "^ 8.0.0." "."gulp-babel": "^" 7.0.1."gulp-clean": "^ 0.4.0"."gulp-clean-css": "^ 4.3.0"."gulp-concat": "^ 2.6.1." "."gulp-file-include": "^ 2.3.0." "."gulp-htmlmin": "^ 5.0.1." "."gulp-imagemin": "^ 7.1.0"."gulp-load-plugins": "^ 2.0.7." "."gulp-rename": "^ 2.0.0." "."gulp-sass": "^ 4.1.0." "."gulp-uglify": "^ 3.0.2." "."gulp-webserver": "^ 0.9.1"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": ""."license": "ISC"."browserslist": [	// CSS compatible version information, please remove the comment in the project
    "FireFox > 2"."IOS > 3"."IE > 7"."chrome > 5"."last 3 version"]}Copy the code

In the process of project development, using this configuration, it will be slow to view the effect. At this time, we can remove the compression of the pipe to improve the speed of viewing the effect