Front end gulp notes

Posted by dirTdogE on Mon, 03 Jan 2022 01:46:50 +0100

GULP

  • gulp is an automated package building tool for project development
  • Based on node environment

What is an automated packaging tool

  • such as

    In the process of development, we will write js files, css files, and so on

    If our project wants to go online, it must be smaller. The smaller the file size, the better

    When we write js files, there will be a lot of line breaks / spaces and so on

    These newlines / spaces are part of the file volume

    Then we need to delete these line breaks / spaces as much as possible before going online

    We can't delete files one by one

    We need an automated tool to help us get rid of these superfluous things

  • This is the meaning of automation tools

  • Common automated packaging build tools

    • gulp
    • webpack

Installing the GULP environment

  • gulp is also a running environment

  • But this environment depends on the node environment

  • So before installing the gulp environment, make sure that the node environment is installed

    • $ node --version
    • $ npm --version
  • The reason why we also want to detect the following npm environment is that we want to use npm to install gulp environment

  • We can install a gulp global package directly

    # Open command line (MAC terminal)
    # Just use npm to install it directly
    
    # windows instruction
    $ npm install --global gulp
    # MAC instruction
    $ sudo npm install --global gulp
    
  • Just wait for the installation. The latest stable version will be installed by default

  • If you want to confirm that the following gulp is installed successfully

  • You can directly use instructions on the command line (terminal) to view the following version numbers

    • $ gulp --version
    • A CLI version: x.x.x appears
    • It means that the installation is successful
  • After installing the gulp environment, we can use it

Why use gulp

  • In our development process

    As we write code, it will automatically help us compress / merge / obfuscate / transcode /

    Because gulp runs based on the node environment, it can provide us with a server

    Let our project start on the server to achieve an automatic refresh and automatic synchronization function

    Because of the emergence of the server, we can use the server proxy when requesting some data

  • When we use gulp, all our source code will use gulp for compression / transcoding

  • And will eventually put it in a new folder for us

    • In other words, our source code is in one folder, and all files after compression / transcoding are in one folder

Use GULP

  • Our gulp environment has been installed. Next, we will use gulp to package our project

1. Create a project

  • We will use gulp to manage our projects

  • First, we need a project to appear

  • Here I'll create one called gulp_test folder as my project folder

  • Because we are working on a project, we will certainly download dependent packages, so we'd better use npm to manage them

  • First do a $npm init initialization

    # Enter project folder
    $ cd gulp_test
    # Manage our projects with npm
    $ npm init -y
    
  • Next, we will decide the directory structure of our source code

  • Create a file called gulpfile in the project directory JS file

    This file is the rule file when gulp is running

    gulp runs as you write in gulpfile JS file

    For example, we want to define:

    • Which files are packaged as css files

    • Which files are packaged as js files

    • Different files have different packaging rules

    Because the directory structure of each project may be different

    Therefore, each project will have its own gulpfile JS file to specify your own rules

  • I will prepare a directory called src as all my source code

    - gulp_text             Project folder
      - src					Project source directory
        + css				deposit css All documents
        + data				Storing data files
        + js				deposit js All documents
        + lib				Store some third-party and public resources( swiper/utils/...)
        + pages				Store all pages
        + sass   			deposit sass All documents
        - static			Store all static resource files
          + audios          Store all audio files
          + images			Store all picture files
          + videos			Store all video files
      - gulpfile.js         Of the project gulp Packaging rules
      - package.json        npm Project management documents
    

2. Download gulp in the project

  • Just now we installed the global gulp

  • It just provides our computer with an environment that can run gulp commands

  • If our project wants to use the gulp tool, we need to download the project dependent gulp in the project

  • Let's download a project dependency gulp first

    # Download project dependent gulp
    $ npm install --save-dev gulp
    
  • When the download is complete, click package There will be corresponding records in the JSON file

    {
        "devDependencies": {
            "gulp": "^4.0.2"
        }
    }
    
    • We'll see that what we install is gulp@4.0.2 Version of
    • This is a relatively new and stable version at present
  • Then we're in gulpfile Introduce gulp dependency into JS file

    // gulpfile.js
    
    // Introducing gulp dependency
    const gulp = require('gulp')
    
  • Next, we can start specifying our packaging rules

3. Several common API s of gulp

  • First of all, we should know that gulp packages code by tasks

    such as

    • We specify a task to package css

    • Let's make a task of packaging js

    As soon as we execute this css task in the future, we will compress the css code

    For all our files, we just create tasks one by one and let them execute them in turn

  • Next, let's talk about some common APIs in gulp

    1. gulp.task(): used to create tasks

      task('css', function () {})

      First parameter: what is the name of this task

      Second parameter: what does this task do

    2. gulp.src(): matching files, that is, which files we want to operate on

      src('./src/css/**')

      The first parameter is the path of the file to be matched (it can take many forms)

      • ./ src/css/index.css: match a file

      • ./ src/css/*.css: all suffixes in the matching CSS folder are CSS file

      • ./ src/css / * *: matches all files in the css folder

      • ./ src/**/*.css: matches all directories under Src css suffix file

      • These are some of the ways we often use, and there are many other ways

      • Need to learn, you can refer to

    3. gulp.pipe(): pipe function, used to do things for us

      Pipe (compressed css)

      Parameters can be various plug-ins, which are used to help us do things

      • For example, you can do something to automatically prefix css attributes

      • Do a compressed css file thing

      • Wait

    4. gulp.dest(): used to write files

      dest('./dist')

      First parameter: a directory address

      As long as it is used to write our compressed files to which folder

      If the folder does not exist, it will be created automatically

    5. gulp.series(): task execution chain of gulp

      series()

      You can fill in many parameters, and each parameter is a task name

      Will perform tasks in the order you write

      • The writing method is to separate the tasks according to their names

      • gulp.series('css', 'js')

      • A css task will be executed first, and then the js task will be executed

      The last parameter (optional): function, the callback function that will be executed after all the tasks you have arranged are executed

    6. gulp.parallel(): task execution chain of gulp

      parallel()

      Multiple tasks can be filled in, and several tasks will be executed synchronously

      parallel('css', 'js')

      • Will start two tasks at the same time

      • The two tasks started in parallel

    7. gulp.watch(): monitor file changes

      watch('./src/css/*.css', function () {})

      First parameter: file path to be monitored

      The second parameter: you need a function to do when the file you monitor changes

4. Create a compressed css task

  • The next step is to create a compressed css file using gulp

  • We certainly can't delete the spaces ourselves or write a piece of code to replace them

  • Instead, you use a dependency package related to gulp

    • $ npm install --save-dev gulp-cssmin
  • Just download it and use it directly

    // gulpfile.js
    
    // Introducing gulp dependency
    const gulp = require('gulp')
    
    // Introducing gulp cssmin dependency
    const cssmin = require('gulp-cssmin')
    
    // Create a css task
    gulp.task('css', function () {
        return gulp
            .src('./src/css/*.css')  // Use the src method to find the file we want to compress
            .pipe(cssmin())          // Perform a compression behavior using pipeline functions
            .pipe(gulp.dest('./dist/css'))  // Put the compressed files in the css folder under the dist folder
    })
    
    • In this way, our simple task of compressing css files is completed
    • Next, just let the task perform the following
  • We went to the command line (terminal) to perform the task we wrote called css

    # Use gulp instructions to perform this css task
    $ gulp css
    
    • After execution, you will find an additional dist folder
    • There is a css folder inside
    • There is one in it css file, this is the compressed file

Auto prefix

  • In fact, our compression is OK here

  • But sometimes we need to prefix some attributes

    • -webkie-transition: all 1s;
    • -webkit-animation: move 1s;
    • ...
  • So we'd better have a tool to help us automatically add prefixes that should be added

  • In this way, we don't need to consider when writing css, so we can write it normally

  • Still use a dependency package related to gulp

    • $ npm install --save-dev gulp-autoprefixer
  • After downloading, we can use it directly

    // gulpfile.js
    
    // Introducing gulp dependency
    const gulp = require('gulp')
    
    // Introducing gulp cssmin dependency
    const cssmin = require('gulp-cssmin')
    
    // Introducing gulp autoprefixer dependency
    const autoprefiexer = require('gulp-autoprefixer')
    
    // Create a css task
    gulp.task('css', function () {
        return gulp
            .src('./src/css/*.css')
            .pipe(autoprefiexer({  // Perform a task of automatically adding prefixes
            	browsers: ['last 2 versions']  // This parameter refers to compatibility with the latest two browser versions
        	}))
            .pipe(cssmin())
            .pipe(gulp.dest('./dist/css'))
    })
    
    • This automatic prefix requires parameters

    • After we add this behavior, we can execute the css task on the command line (terminal)

    • You will find dist / CSS / xxx The code in the CSS file is automatically prefixed

    • But you will find that "it seems that an error is reported" on the command line

      [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-kzEtCFtt-1628940627644)(./assets/css_auto.png)]

    • This is not an error report, it's a reminder

    • Because autoprefixer can fill in many parameters

    • In recent versions of gulp, you can write parameters directly in gulpfile JS file is not very comfortable

    • It's not very formal, so I suggest you create a new one under the root directory Browserlist file to write or write in package JSON is OK. It looks more formal

  • Let's move the parameters just written to package JSON file

    // package.json
    {
        "name": "gulp_test",
        "version": "1.0.0",
        "description": "",
        "main": "index.js",
        "scripts": {
            "test": "echo \"Error: no test specified\" && exit 1"
        },
        "keywords": [],
        "author": "",
        "license": "ISC",
        "devDependencies": {
            "gulp": "^4.0.2",
            "gulp-autoprefixer": "^7.0.0",
            "gulp-cssmin": "^0.2.0"
        },
        {
    		"browserslist": [
        		"last 2 versions"
        	]
    	}
    }
    
    • Then you can put gulpflie The parameters in the JS file are deleted, leaving only autoprefixer()
    • Then go to the command line (terminal) to execute css tasks
    • We will find that the prefix is still added automatically, and there is no "error"
  • We are interested in the package Many other parameters can be added to the writing in JSON

  • Can let him do more compatible processing

    // browserslist
    {
        "browsers": [
            "last 2 versions",
            "iOS 7",
            "FireFox > 20",
            "Android > 4.1"
        ]
    }
    
    • We can write in various versions you want to be compatible with
    • Then, when executing, you will find that more and more prefix contents and compatibility processing have been added
    • Here is just a part. If you want to know more, you can refer to it Nuggets

5. Create a task to compress sass

  • We have solved the content of css. Next, we need to solve the task of sass

  • In fact, it is similar to the css task, but there is one more step

  • It is to convert the content of sass into the content of css, and then automatically add a prefix, compress it and put it in the specified directory

  • Transforming sass content also requires a gulp related dependency

    • $ npm install --save-dev gulp-sass
    • When downloading here, it may fail and report an error
    • If an error is reported, we will first install a node sass dependency and then install gulp sass
    • $ npm install --save-dev node-sass
    • $ npm install --save-dev gulp-sass
  • After downloading, we'll just use it

    // gulpfile.js
    
    // Introducing gulp dependency
    const gulp = require('gulp')
    
    // Introducing gulp cssmin dependency
    const cssmin = require('gulp-cssmin')
    
    // Introducing gulp autoprefixer dependency
    const autoprefiexer = require('gulp-autoprefixer')
    
    // Introducing gulp sass dependency
    const sass = require('gulp-sass')
    
    // Task of compressing css
    gulp.task('css', function () { ... })
    
    // Task of compressing sass
    gulp.task('sass', function () {
        return gulp
            .src('./src/sass/*.scss')
            .pipe(sass())  // Convert sass syntax to css syntax before automatically adding prefixes
            .pipe(autoprefiexer())
            .pipe(cssmin())
            .pipe(gulp.dest('./dist/css'))
    })
    
    • It is basically the same as the css task, except that the syntax is changed before the prefix is automatically added

    • Because it's the same after parsing css files, so we just put them in the css folder

    • Then you can go to the command line (terminal) to execute sass

      # Perform the sass task
      $ gulp sass
      
    • We will find that the files we wrote in the sass folder are transcoded and compressed in the dist/css / folder

6. Create a task to compress JavaScript

  • Next, we will do a task to compress js files

  • In fact, it is the same as the previous routine

  • The compression of js files here also requires a gulp related dependency package

    • $ npm install --save-dev gulp-uglify
  • After downloading, we'll configure it

    // gulpfile.js
    
    // Introducing gulp dependency
    const gulp = require('gulp')
    
    // Introducing gulp cssmin dependency
    const cssmin = require('gulp-cssmin')
    
    // Introducing gulp autoprefixer dependency
    const autoprefiexer = require('gulp-autoprefixer')
    
    // Introducing gulp sass dependency
    const sass = require('gulp-sass')
    
    // Introducing gulp uglify dependency
    const uglify = require('gulp-uglify')
    
    // Task of compressing css
    gulp.task('css', function () { ... })
    
    // Task of compressing sass
    gulp.task('sass', function () { ... })
    
    // Task of compressing js
    gulp.task('js', function () {
        return gulp
            .src('./src/js/*.js')
            .pipe(uglify())
            .pipe(gulp.dest('./dist/js'))
    })
    
    • A simple task of compressing js is done

    • Let's go to the command line (terminal) to perform the following task

      # Perform the following js tasks
      $ gulp js
      
    • You will find that there is a js folder under dist, which contains our js code, which has been compressed

    • However, when we write the syntax of es6(ES2015), we can't compress it normally, and an error will be reported

    • Because this gulp uglify doesn't know the syntax of es6(ES2015)

ES6 to ES5

  • Then we need to do one thing

  • Before uglify, convert the syntax from es6 to es5

  • In this way, there is no problem in compression

  • Three dependent packages need to be downloaded from es6 to es5

    # Three dependencies required for es6 to es5
    $ npm install --save-dev gulp-babel
    $ npm install --save-dev @babel/core
    $ npm install --save-dev @babel/preset-env
    
  • After downloading, we can configure it

  • Although three dependent packages have been downloaded, we only need to import a gulp Babel

    // gulpfile.js
    
    // Introducing gulp dependency
    const gulp = require('gulp')
    
    // Introducing gulp cssmin dependency
    const cssmin = require('gulp-cssmin')
    
    // Introducing gulp autoprefixer dependency
    const autoprefiexer = require('gulp-autoprefixer')
    
    // Introducing gulp sass dependency
    const sass = require('gulp-sass')
    
    // Introducing gulp uglify dependency
    const uglify = require('gulp-uglify')
    
    // Introducing gulp Babel dependency
    const babel = require('gulp-babel')
    
    // Task of compressing css
    gulp.task('css', function () { ... })
    
    // Task of compressing sass
    gulp.task('sass', function () { ... })
    
    // Task of compressing js
    gulp.task('js', function () {
        return gulp
            .src('./src/js/*.js')
        	.pipe(babel({ // Transcoding is required before compression
            	presets: ['@babel/env'] // A parameter is required
        	}))
            .pipe(uglify())
            .pipe(gulp.dest('./dist/js'))
    })
    
    • Just perform babel transcoding before compressing js
    • It's the same. We need a parameter. We can write it directly in this
    • After executing js again, we found that the compressed content was converted into es5 syntax

7. Create a compressed HTML task

  • Next, we will compress the html file

  • It's still our routine. Do it again

  • Compressing html files requires a gulp dependent package

    • $ npm install --save-dev gulp-htmlmin
  • After downloading, we can configure it

    // gulpfile.js
    
    // Introducing gulp dependency
    const gulp = require('gulp')
    
    // Introducing gulp cssmin dependency
    const cssmin = require('gulp-cssmin')
    
    // Introducing gulp autoprefixer dependency
    const autoprefiexer = require('gulp-autoprefixer')
    
    // Introducing gulp sass dependency
    const sass = require('gulp-sass')
    
    // Introducing gulp uglify dependency
    const uglify = require('gulp-uglify')
    
    // Introducing gulp Babel dependency
    const babel = require('gulp-babel')
    
    // Introducing gulp htmlmin dependency
    const htmlmin = require('gulp-htmlmin')
    
    // Task of compressing css
    gulp.task('css', function () { ... })
    
    // Task of compressing sass
    gulp.task('sass', function () { ... })
    
    // Task of compressing js
    gulp.task('js', function () { ... })
    
    // Task of compressing html
    gulp.task('html', function () {
        return gulp
            .src('./src/pages/*.html')  // file found
            .pipe(htmlmin({ // Compress using htmlmin
                removeComments: true,
                removeEmptyAttributes: true,
                collapseWhitespace: true,
                collapseBooleanAttributes: true,
                minifyCSS: true,
                minifyJS: true
        	}))
            .pipe(gulp.dest('./dist/pages')) // Put it in the specified directory
    })
    
    • Note: gulp HTML min needs to pass parameters when used

      • removeComments: remove comments
      • removeEmptyAttributes: remove empty attributes
      • collapseWhitespace: remove spaces and line breaks
      • Collapsepooleanattributes: whether to simplify attributes with Boolean attribute values (checked="checked")
      • minifyCSS: whether to compress the style tags given in the page (embedded css code)
      • minifyJS: whether to compress the script tag of the page (embedded js code)
    • At this time, you can go to the command line (terminal) to execute the task of html

      # Perform the following task
      $ gulp html
      

HTML import component

  • One of the more interesting things here is that we can import components in html files

  • such as

    • When we write a web page, the head and bottom are generally public content
    • Then we can extract the head and bottom separately and write them into an html fragment
    • Then, when using each page, we just need to introduce the header and bottom fragments
    • You don't have to write every page
  • The import of this component must be completed before compressing html

  • Let's prepare a directory to store all html fragments

    • I will create a new folder called components in the src directory

    • Used to store all html fragment files

    • Write a header in it HTML as a header fragment

      <!-- src/conponents/header.html -->
      <div class="header">
          <h1 class="logo"></h1>
          <p>I am a public head</p>
      </div>
      
  • Next, we download a gulp dependency that can import html fragments

    • $ npm install --save-dev gulp-file-include
  • Then we configure it

    // gulpfile.js
    
    // Introducing gulp dependency
    const gulp = require('gulp')
    
    // Introducing gulp cssmin dependency
    const cssmin = require('gulp-cssmin')
    
    // Introducing gulp autoprefixer dependency
    const autoprefiexer = require('gulp-autoprefixer')
    
    // Introducing gulp sass dependency
    const sass = require('gulp-sass')
    
    // Introducing gulp uglify dependency
    const uglify = require('gulp-uglify')
    
    // Introducing gulp Babel dependency
    const babel = require('gulp-babel')
    
    // Introducing gulp htmlmin dependency
    const htmlmin = require('gulp-htmlmin')
    
    // Introduce gulp file include dependency
    const fileinclude = require('gulp-file-include')
    
    // Task of compressing css
    gulp.task('css', function () { ... })
    
    // Task of compressing sass
    gulp.task('sass', function () { ... })
    
    // Task of compressing js
    gulp.task('js', function () { ... })
    
    // Task of compressing html
    gulp.task('html', function () {
        return gulp
            .src('./src/pages/*.html')  // file found
            .pipe(fileinclude({ // Import html fragment
                  prefix: '@-@',  // You can customize an identifier
                  basepath: './src/components'  // html fragment storage path
            }))
            .pipe(htmlmin({ // Compress using htmlmin
                removeComments: true,
                removeEmptyAttributes: true,
                collapseWhitespace: true,
                collapseBooleanAttributes: true,
                minifyCSS: true,
                minifyJS: true
        	}))
            .pipe(gulp.dest('./dist/pages')) // Put it in the specified directory
    })
    
    • We need to import html fragments before html min is compressed
    • This dependency needs to pass some parameters
      • prefix: customize an identifier to know in our page that my next thing is to be imported
      • basepath: the directory where html fragment files are stored
  • Next, we just need to import in the html file

    <!-- src/pages/index.html -->
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>Document</title>
        </head>
        <body>
            <!--
                This is the import fragment. You can use the identifier defined by ourselves
                include Write parameters directly html Just the file name of the clip
                Because we configured it before html The storage path of the fragment
                He will automatically go to our configuration basepath Find it inside
            -->
            @-@include('header.html')
        </body>
    </html>
    
  • At this time, we can go to the command line (terminal) to execute html tasks

    # Perform an html task
    $ gulp html
    
    • At this time, we find that the position where we write @- @ include('header.html ') is replaced by our position in header All the content written in the HTML file

Import HTML fragment pass parameters

  • When importing html fragments, we can also pass some parameters to the fragments

  • The identifier we defined before is still used

    <!-- src/conponents/header.html -->
    <div class="header">
        <h1 class="logo"></h1>
        <p>I am a public head</p>
        <!-- This means in span One is required inside the label title Filled with variables -->
        <span>@-@title</span>
    </div>
    
  • We can pass parameters when importing this fragment in the page

    <!-- src/pages/index.html -->
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>Document</title>
        </head>
        <body>
            <!--
                We can pass some parameters when importing
                Note: when passing parameters, be sure to write json If the format is not recognized, an error will be reported
            -->
            @-@include('header.html', { "title": "hello world" })
        </body>
    </html>
    
  • In this way, we run the command to package html again, and the result is

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>Document</title>
        </head>
        <body>
            <div class="header">
                <h1 class="logo"></h1>
                <p>I am a public head</p>
                <span>hello world</span>
            </div>
        </body>
    </html>
    

8. Create a compressed picture task

  • Next we will compress the picture

  • Compressing pictures is much simpler. It's still the same routine

  • We need to use a gulp related dependency to compress the image

    • $ npm install --save-dev gulp-imagemin
    • This dependency will be downloaded for a long time, and it will stop for a period of time
    • It doesn't fail, because it will download many other dependencies, so it takes a long time
    • Just wait
  • After downloading, we can configure it

    // gulpfile.js
    
    // Introducing gulp dependency
    const gulp = require('gulp')
    
    // Introducing gulp cssmin dependency
    const cssmin = require('gulp-cssmin')
    
    // Introducing gulp autoprefixer dependency
    const autoprefiexer = require('gulp-autoprefixer')
    
    // Introducing gulp sass dependency
    const sass = require('gulp-sass')
    
    // Introducing gulp uglify dependency
    const uglify = require('gulp-uglify')
    
    // Introducing gulp Babel dependency
    const babel = require('gulp-babel')
    
    // Introducing gulp htmlmin dependency
    const htmlmin = require('gulp-htmlmin')
    
    // Introduce gulp file include dependency
    const fileinclude = require('gulp-file-include')
    
    // Introducing gulp imagemin dependency
    const imagemin = require('gulp-imagemin')
    
    // Task of compressing css
    gulp.task('css', function () { ... })
    
    // Task of compressing sass
    gulp.task('sass', function () { ... })
    
    // Task of compressing js
    gulp.task('js', function () { ... })
    
    // Task of compressing html
    gulp.task('html', function () { ... })
    
    // Task of compressing image
    gulp.task('image', function () {
        return gulp
            .src('./src/static/images/**')
            .pipe(imagemin({  // Perform compression tasks
                progressive: true,  // lossless compression
                optimizationLevel: 7  // Compression level 1 ~ 7
            }))
            .pipe(gulp.dest('./dist/static/images'))
    })
    
    • When we first look for files, we don't limit suffixes, because we have a lot of picture suffixes
    • At this time, the task of compressing the image is configured
    • We can go to the command line (terminal) to perform the task
    # Execute image task
    $ gulp image
    
  • Because we are lossless compression, in fact, the compression of pictures can't compress too many things

  • Even if you don't turn on lossless compression, it won't change much

  • It's just that when there are too many and too large pictures, more things will be compressed

9. Tasks of other resources and static resources

  • That's basically what we're going to compress

  • We can't compress the rest, such as video and audio

  • Including the content in our lib, it is a third-party, and we don't need to compress it

  • Let's just transfer them directly. Just put them in the dist folder

  • There's no need to rely on it here. Let's just transfer it directly

    // gulpfile.js
    
    // Introducing gulp dependency
    const gulp = require('gulp')
    
    // Introducing gulp cssmin dependency
    const cssmin = require('gulp-cssmin')
    
    // Introducing gulp autoprefixer dependency
    const autoprefiexer = require('gulp-autoprefixer')
    
    // Introducing gulp sass dependency
    const sass = require('gulp-sass')
    
    // Introducing gulp uglify dependency
    const uglify = require('gulp-uglify')
    
    // Introducing gulp Babel dependency
    const babel = require('gulp-babel')
    
    // Introducing gulp htmlmin dependency
    const htmlmin = require('gulp-htmlmin')
    
    // Introduce gulp file include dependency
    const fileinclude = require('gulp-file-include')
    
    // Introducing gulp imagemin dependency
    const imagemin = require('gulp-imagemin')
    
    // Task of compressing css
    gulp.task('css', function () { ... })
    
    // Task of compressing sass
    gulp.task('sass', function () { ... })
    
    // Task of compressing js
    gulp.task('js', function () { ... })
    
    // Task of compressing html
    gulp.task('html', function () { ... })
    
    // Task of compressing image
    gulp.task('image', function () { ... })
    
    // Transfer video
    gulp.task('video', function () {
        return gulp
        	.src('./src/static/videos/**')
            .pipe(gulp.dest('./dist/static/video'))
    })
    
    // Transfer audio
    gulp.task('audio', function () { ... })
    
    // Transfer lib
    gulp.task('lib', function () { ... })
    
    // Transfer data
    gulp.task('data', function () { ... })
    
    • Because the transfer tasks are the same, I won't write them one by one, just transfer them to the past

10. Create a default task

  • Our tasks have been created, but we found that the tasks are executed one by one

  • We can't perform one task at a time

  • So we can create a task separately. The function of this task is to execute all other tasks

  • The newly created task is called default

    • Because when you run the gulp command on the command line (terminal)
    • If the task name is not written, the default task will be executed by default
    // gulpfile.js
    
    // Introducing gulp dependency
    const gulp = require('gulp')
    
    // Introducing gulp cssmin dependency
    const cssmin = require('gulp-cssmin')
    
    // Introducing gulp autoprefixer dependency
    const autoprefiexer = require('gulp-autoprefixer')
    
    // Introducing gulp sass dependency
    const sass = require('gulp-sass')
    
    // Introducing gulp uglify dependency
    const uglify = require('gulp-uglify')
    
    // Introducing gulp Babel dependency
    const babel = require('gulp-babel')
    
    // Introducing gulp htmlmin dependency
    const htmlmin = require('gulp-htmlmin')
    
    // Introduce gulp file include dependency
    const fileinclude = require('gulp-file-include')
    
    // Introducing gulp imagemin dependency
    const imagemin = require('gulp-imagemin')
    
    // Task of compressing css
    gulp.task('css', function () { ... })
    
    // Task of compressing sass
    gulp.task('sass', function () { ... })
    
    // Task of compressing js
    gulp.task('js', function () { ... })
    
    // Task of compressing html
    gulp.task('html', function () { ... })
    
    // Task of compressing image
    gulp.task('image', function () { ... })
    
    // Transfer video
    gulp.task('vider', function () { ... })
    
    // Transfer audio
    gulp.task('audio', function () { ... })
    
    // Transfer lib
    gulp.task('lib', function () { ... })
    
    // Transfer data
    gulp.task('data', function () { ... })
    
    // Create default task
    gulp.task('default', gulp.parallel('css', 'sass', 'js', 'html', 'image', 'video', 'audio', 'lib', 'data'))
    
    • The second parameter of the default task does not need to pass a function

    • Because gulp Parallel () will return a function and put it here

    • We don't need to do these tasks in order, just execute them in parallel

    • At this time, we just need to execute the default task on the command line (terminal)

      # Perform default tasks
      $ gulp
      
      • That's it.
      • We didn't write the task name. The default task will be executed automatically
      • The default task will execute all other tasks

11. Create a DEL task

  • At this point, gulp is basically not a problem

  • However, once we change the name of a file in a folder, we will find it when packaging

  • The packaged content does not change the original name, but has one more content

  • In other words, I still keep my previous content

  • Then we need to solve this problem

    • It is best to delete the dist folder before each package
    • Then we're packing
    • In this way, every time it comes out, it is packaged according to the source code in the latest src directory
    • There will be no superfluous content
  • To delete a folder, we need to use a dependency

    • $ npm install --save-dev del
  • Then we introduce it for configuration

    // gulpfile.js
    
    // Introducing gulp dependency
    const gulp = require('gulp')
    
    // Introducing gulp cssmin dependency
    const cssmin = require('gulp-cssmin')
    
    // Introducing gulp autoprefixer dependency
    const autoprefiexer = require('gulp-autoprefixer')
    
    // Introducing gulp sass dependency
    const sass = require('gulp-sass')
    
    // Introducing gulp uglify dependency
    const uglify = require('gulp-uglify')
    
    // Introducing gulp Babel dependency
    const babel = require('gulp-babel')
    
    // Introducing gulp htmlmin dependency
    const htmlmin = require('gulp-htmlmin')
    
    // Introduce gulp file include dependency
    const fileinclude = require('gulp-file-include')
    
    // Introducing gulp imagemin dependency
    const imagemin = require('gulp-imagemin')
    
    // Introducing del dependency
    const del = require('del')
    
    // Task of compressing css
    gulp.task('css', function () { ... })
    
    // Task of compressing sass
    gulp.task('sass', function () { ... })
    
    // Task of compressing js
    gulp.task('js', function () { ... })
    
    // Task of compressing html
    gulp.task('html', function () { ... })
    
    // Task of compressing image
    gulp.task('image', function () { ... })
    
    // Transfer video tasks
    gulp.task('vider', function () { ... })
    
    // Transfer audio tasks
    gulp.task('audio', function () { ... })
    
    // Transfer lib tasks
    gulp.task('lib', function () { ... })
    
    // Transfer data tasks
    gulp.task('data', function () { ... })
    
    // Delete dist's task
    gulp.task('del', function () {
        return del('./dist')
    })
    
    // Create default task
    gulp.task('default', gulp.parallel('css', 'sass', 'js', 'html', 'image', 'video', 'audio', 'lib', 'data'))
    
    • Just tell him which folder we deleted when we used it
    • At this time, when we run the del task, we will find that the dist folder has been deleted

12. Progressive implementation of the mandate

  • After we have created the del task, the next step is to put it in the task queue

  • However, if it is parallel to other tasks, it is not necessarily which task is completed first

  • Problems will arise at this time

    • If the deleted task is completed first and the others are completed later, then there is nothing to do
    • However, if other tasks are completed first and then deleted, the packaged files will be deleted again
  • Therefore, we can use gulp Series() to complete the task in sequence

    • Because the task of the second parameter of this method will be executed after the task of the first parameter is completed
  • We just need to modify our default task. There is no need to change anything else

    // gulpfile.js
    
    // Create default task
    gulp.task('default', gulp.series(
    	'del',
        gulp.parallel('css', 'sass', 'js', 'html', 'image', 'video', 'audio', 'lib', 'data')
    ))
    
    • We pass two parameters in the series() task
      • The first parameter is del
      • The second parameter is to perform some other tasks in parallel
    • In this case, as soon as we run the default task
      • The del task will be executed first. When the del task is completed, the dist folder has been deleted
      • Will continue to perform our other packaging and compression tasks
      • There will be no problem

13. Create a monitoring task

  • Our gulpfile JS file configuration up to now, basically almost

  • But we found a problem, that is, every time I modify the source code, I have to execute the default task to synchronize

  • Then we need a monitoring task to monitor the changes of my folder. As long as the folder changes, pack and compress it again

  • Here, we do not need to rely on, but use gulp Just use watch () to monitor files

    // gulpfile.js
    
    // Introducing gulp dependency
    const gulp = require('gulp')
    
    // Introducing gulp cssmin dependency
    const cssmin = require('gulp-cssmin')
    
    // Introducing gulp autoprefixer dependency
    const autoprefiexer = require('gulp-autoprefixer')
    
    // Introducing gulp sass dependency
    const sass = require('gulp-sass')
    
    // Introducing gulp uglify dependency
    const uglify = require('gulp-uglify')
    
    // Introducing gulp Babel dependency
    const babel = require('gulp-babel')
    
    // Introducing gulp htmlmin dependency
    const htmlmin = require('gulp-htmlmin')
    
    // Introduce gulp file include dependency
    const fileinclude = require('gulp-file-include')
    
    // Introducing gulp imagemin dependency
    const imagemin = require('gulp-imagemin')
    
    // Introducing del dependency
    const del = require('del')
    
    // Task of compressing css
    gulp.task('css', function () { ... })
    
    // Task of compressing sass
    gulp.task('sass', function () { ... })
    
    // Task of compressing js
    gulp.task('js', function () { ... })
    
    // Task of compressing html
    gulp.task('html', function () { ... })
    
    // Task of compressing image
    gulp.task('image', function () { ... })
    
    // Transfer video tasks
    gulp.task('vider', function () { ... })
    
    // Transfer audio tasks
    gulp.task('audio', function () { ... })
    
    // Transfer lib tasks
    gulp.task('lib', function () { ... })
    
    // Transfer data tasks
    gulp.task('data', function () { ... })
    
    // Delete dist's task
    gulp.task('del', function () { ... })
    
    // Create a task to monitor changes
    gulp.task('watch', function () {
      gulp.watch('./src/css/*.css', gulp.series('css'))
      gulp.watch('./src/sass/*.sass', gulp.series('sass'))
      gulp.watch('./src/js/*.js', gulp.series('js'))
      gulp.watch('./src/pages/*.html', gulp.series('html'))
      gulp.watch('./src/lib/**', gulp.series('lib'))
      gulp.watch('./src/data/**', gulp.series('data'))
      gulp.watch('./src/static/images/**', gulp.series('image'))
      gulp.watch('./src/static/videos/**', gulp.series('video'))
      gulp.watch('./src/static/audios/**', gulp.series('audio'))
    })
    
    // Create default task
    gulp.task('default', gulp.series(
    	'del',
        gulp.parallel('css', 'sass', 'js', 'html', 'image', 'video', 'audio', 'lib', 'data'),
        'watch'
    ))
    
    • After we have created the watch task, just execute it in the default task
    • Let's just put him in the third task list
    • This will start monitoring after all the files are packaged
  • At this time, when we execute the default task again

    • The exit instruction will not be packaged
    • Will be flashing and waiting
    • Then you modify all the files and they will be repackaged and compiled automatically
  • At this time, for example

    • When you modify the contents in the src/css directory, you will automatically re execute the css task
    • When you modify the contents in the src/sass directory, the sass task will be automatically re executed
  • Then the contents in our dist folder are the contents synchronized with our src directory in real time

14. Tasks of automatically opening browser and hot refresh

  • Why do we have to synchronize dist and src

  • Because we can rely on gulp to automatically open a browser page for us

  • As we write, we don't need to refresh the browser manually. It will refresh the browser automatically

  • In other words, we just need to write, it will refresh automatically, and we can see the results directly

  • Automatic browser opening and hot refresh require a dependency

    • $ npm install --save-dev gulp-webserver
  • After downloading, we can configure it

    // gulpfile.js
    
    // Introducing gulp dependency
    const gulp = require('gulp')
    
    // Introducing gulp cssmin dependency
    const cssmin = require('gulp-cssmin')
    
    // Introducing gulp autoprefixer dependency
    const autoprefiexer = require('gulp-autoprefixer')
    
    // Introducing gulp sass dependency
    const sass = require('gulp-sass')
    
    // Introducing gulp uglify dependency
    const uglify = require('gulp-uglify')
    
    // Introducing gulp Babel dependency
    const babel = require('gulp-babel')
    
    // Introducing gulp htmlmin dependency
    const htmlmin = require('gulp-htmlmin')
    
    // Introduce gulp file include dependency
    const fileinclude = require('gulp-file-include')
    
    // Introducing gulp imagemin dependency
    const imagemin = require('gulp-imagemin')
    
    // Introducing del dependency
    const del = require('del')
    
    // Task of compressing css
    gulp.task('css', function () { ... })
    
    // Task of compressing sass
    gulp.task('sass', function () { ... })
    
    // Task of compressing js
    gulp.task('js', function () { ... })
    
    // Task of compressing html
    gulp.task('html', function () { ... })
    
    // Task of compressing image
    gulp.task('image', function () { ... })
    
    // Transfer video tasks
    gulp.task('vider', function () { ... })
    
    // Transfer audio tasks
    gulp.task('audio', function () { ... })
    
    // Transfer lib tasks
    gulp.task('lib', function () { ... })
    
    // Transfer data tasks
    gulp.task('data', function () { ... })
    
    // Delete dist's task
    gulp.task('del', function () { ... })
    
    // Create a task to monitor changes
    gulp.task('watch', function () { ... })
    
    // Create a task that automatically opens the browser
    gulp.task('webserver', function () {
      return gulp
        .src('./dist')
        .pipe(webserver({
          host: 'localhost',
          port: 3000,
          open: './pages/index.html',
          livereload: true
        }))
    })
    
    // Create default task
    gulp.task('default', gulp.series(
    	'del',
        gulp.parallel('css', 'sass', 'js', 'html', 'image', 'video', 'audio', 'lib', 'data'),
        'webserver',
        'watch'
    ))
    
    • To automatically open the browser, we must open our packaged files, so our src method needs to find the dist directory to execute
    • Using gulp web server requires configuration of some parameters
      • host: open domain name
      • Port: open port number
      • open: which page is opened by default (just start writing from dist)
      • livereload: whether to refresh the browser automatically
    • Note: the task of webserver should precede the task of watch
      • Because the series method completes the previous task and executes the latter task
      • When the watch task is not completed, it is monitored all the time
      • So if it is written after the watch, there is no way to execute it

Agent configuration

  • Because we started a server

  • If the sending request is not the same as its own content, the same origin policy will be triggered

  • However, our web server can configure proxy

  • Because the server started by gulp is a node server

  • Our agent can only be configured in the web server

    // Create a task that automatically opens the browser
    gulp.task('webserver', function () {
      return gulp
        .src('./dist')
        .pipe(webserver({
          host: 'localhost',
          port: 3000,
          open: './pages/index.html',
          livereload: true,
          proxies: [ // All the proxies are in the array here
              {
                  source: '/a', // Proxy request identifier
                  target: 'https://www.xxx.com '/ / the address you want to represent
              },
              {
                  source: '/b',
                  target: 'https://www.yyy.com'
              }
          ]
        }))
    })
    
    • After this configuration is completed, when you request, you only need to request the address / a or / b
    • The server will forward the request to you and form a reverse proxy to obtain the data

Full profile

  • Put a full version of the configuration file

  • Dependent packages required

    [the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ATr2RLQX-1628940627647)(./assets/gulp dependency package. png)]

  • Full profile

    // gulpfile.js
    
    const gulp = require('gulp')
    const cssmin = require('gulp-cssmin')
    const autoprefiexer = require('gulp-autoprefixer')
    const sass = require('gulp-sass')
    const uglify = require('gulp-uglify')
    const babel = require('gulp-babel')
    const htmlmin = require('gulp-htmlmin')
    const fileinclude = require('gulp-file-include')
    const imagemin = require('gulp-imagemin')
    const del = require('del')
    const webserver = require('gulp-webserver')
    
    gulp.task('css', function () {
      return gulp
        .src('./src/css/*.css')
        .pipe(autoprefiexer())
        .pipe(cssmin())
        .pipe(gulp.dest('./dist/css'))
    })
    
    gulp.task('sass', function () {
      return gulp
        .src('./src/sass/*.scss')
        .pipe(sass())
        .pipe(autoprefiexer())
        .pipe(cssmin())
        .pipe(gulp.dest('./dist/css'))
    })
    
    gulp.task('js', function () {
      return gulp
        .src('./src/js/*.js')
        .pipe(babel({
          presets: ['@babel/env']
        }))
        .pipe(uglify())
        .pipe(gulp.dest('./dist/js'))
    })
    
    gulp.task('html', function () {
      return gulp
        .src('./src/pages/*.html')
        .pipe(fileinclude({
          prefix: '@-@',
          basepath: './src/components'
        }))
        .pipe(htmlmin({
          removeComments: true,
          removeEmptyAttributes: true,
          collapseWhitespace: true,
          collapseBooleanAttributes: true,
          minifyCSS: true,
          minifyJS: true
        }))
        .pipe(gulp.dest('./dist/pages'))
    })
    
    gulp.task('image', function () {
      return gulp
        .src('./src/static/images/**')
        .pipe(imagemin({
          progressive: true,
          optimizationLevel: 7
        }))
        .pipe(gulp.dest('./dist/static/images'))
    })
    
    gulp.task('video', function () {
      return gulp
        .src('./src/static/videos/**')
        .pipe(gulp.dest('./dist/static/video'))
    })
    
    gulp.task('audio', function () {
      return gulp
        .src('./src/static/audios/**')
        .pipe(gulp.dest('./dist/static/audio'))
    })
    
    gulp.task('lib', function () {
      return gulp
        .src('./src/lib/**')
        .pipe(gulp.dest('./dist/lib'))
    })
    
    gulp.task('data', function () {
      return gulp
        .src('./src/data/**')
        .pipe(gulp.dest('./dist/data'))
    })
    
    gulp.task('del', function () {
      return del('./dist')
    })
    
    gulp.task('watch', function () {
      gulp.watch('./src/css/*.css', gulp.series('css'))
      gulp.watch('./src/sass/*.sass', gulp.series('sass'))
      gulp.watch('./src/js/*.js', gulp.series('js'))
      gulp.watch('./src/pages/*.html', gulp.series('html'))
      gulp.watch('./src/lib/**', gulp.series('lib'))
      gulp.watch('./src/data/**', gulp.series('data'))
      gulp.watch('./src/static/images/**', gulp.series('image'))
      gulp.watch('./src/static/videos/**', gulp.series('video'))
      gulp.watch('./src/static/audios/**', gulp.series('audio'))
    })
    
    gulp.task('webserver', function () {
      return gulp
        .src('./dist')
        .pipe(webserver({
          host: 'localhost',
          port: 3000,
          open: './pages/index.html',
          livereload: true,
          proxies: [
            {
              source: '/a',
              target: ''
            }
          ]
        }))
    })
    
    gulp.task('default', gulp.series(
      'del',
      gulp.parallel('css', 'sass', 'js', 'html', 'image', 'video', 'audio', 'lib', 'data'),
      'webserver',
      'watch'
    ))
    

Topics: Front-end