At the beginning of each development, a list of things to do, or a picture of the process, helps to clarify the ideas

Gulp profile

Gulp is the most popular front-end build system. It is efficient and easy to use. It is a stream-based build system. It automates painful or time-consuming tasks in the development process, thereby reducing wasted time and creating more value.

Gulp’s official website lists its three main features, as shown below:

Install and use

Node. Js version needs to be > = 12 | | 14.13.1 | | > = 16

The steps are as follows:

  1. Install gulp into the global environment

    Install gulp command-line tool NPM install –global gulp-cli Install gulp as development dependency NPM install –save-dev gulp

  2. Create the gulpfile.js configuration file and write the build task, which will be automatically loaded when running gulp

    Open the project code to be built, use the package management tool to initialize the project environment, generate package.json file, and create a gulpfile.js file in the same directory as the gulp automatic build configuration file. This file can be quickly generated and opened by running code gulpfile.js on a terminal in Vscode.

  3. Run the gulp task from the command line terminal

    Run the gulp command test in the root directory of the project and see the following message to prove that gulp is successfully installed, but we have not configured the task yet.

Gulp automates the main process of build

Read file — “compress file –” write file (all in stream mode)

Gulp exposes SRC () and dest() methods for handling files stored on the computer. SRC () : reads the file to generate a Node stream. Dest () : Generates a Node stream, usually as a termination stream

The main API provided by streams is the.pipe() method, which is used to connect to transformed or writable streams.

SRC and DEST need to be introduced before creating a task

// Introduce using the Common JS specification
const { src, dest } = require('gulp')
Copy the code

Create a task

You can search through the glUP official website plug-in library as required. Basically, each plug-in provides a function, and the result of function call will return a transformation flow, so that you can implement the transformation in a file.

Yarn gulp-clean-css –dev is used to install the yarn gulp-clean-css

const { src, dest } = require('gulp');
/ / compress CSS
const cleanCss = require('gulp-clean-css');

function streamTask() {
  return src('src/*.css', { base: 'src' })  // base: base path, specified as SRC original directory output
  .pipe(cleanCss())
  .pipe(dest('dist'))}exports.default = streamTask;  // Export the default task
/ / or
module.export = { streamTask } // Export the named task
Copy the code

Run the yarn gulp command to execute the default task of gulpfile.js (yarn gulp streamTask performs the specified task). The following figure shows that the index. CSS file in the SRC directory is compressed successfully.

CSS: SRC CSS in the root directory SRC /**/* CSS: wildcard mode of subfiles SRC CSS in any subdirectory SRC /** : SRC All files in any subdirectory

Combination of task

Gulp provides two powerful composition methods, series() and Parallel (), which allow multiple independent tasks to be combined into a larger operation

Series () : to execute tasks in sequence parallel() : to execute multiple tasks simultaneously

const { src, dest, series, parallel } = require('gulp');
function css() {... }function html() {... }function js() {... }// CSS, HTML, js do not affect each other and can be executed at the same time
const complicate = parallel(cssStyle, sassStyle, js, page)

module.exports = {
  complicate
};
Copy the code

Configure the hot update development server

Use the browser – sync

const browserSync = require('browser-sync')
const bs = browserSync.create()

function serve() {
    bs.init({
        server: {
            baseDir: 'dir'}})}Copy the code

A basic automated build complete configuration is as follows:

Main functions:

  • Convert SCSS, HTML template, ES6
  • Compress CSS, HTML, JS, images, font files
  • Output static file
  • Remove the file
  • File reference handling (building comment transformations)
  • Listening for file changes
  • Configure the hot update development server
  • Expose public tasks (clean, dev, build)
/** * SRC read stream, dest terminate/output stream; * Combined tasks: series series; Dist **/ **/ **/ **/ **/ **/ **/ **/ **/ **/ **/ **/

const { src, dest, series, parallel, watch } = require('gulp');
// // Clear files in series. You need to delete files before performing construction tasks
const del = require('del')
/ / compress CSS
const cleanCss = require('gulp-clean-css');
/ / renamed
const rename = require('gulp-rename');
// gulp-sass sass: convert sass to CSS
const sass = require('gulp-sass') (require('sass'));
// gulp-babel@babel/core@babel /preset-env: preset script, preset new features in ES6 and above
const babel = require('gulp-babel')
// HTML template file conversion
const swig = require('gulp-swig')
// image file conversion, imagemin through C++ module, need to download binary assembly (download on github)
/** * gulp image Error [ERR_REQUIRE_ESM]: /** * gulp image Error [ERR_REQUIRE_ESM]: require() of ES Module gulpfile.js not supported. Instead change the require of index.js * */
const imagemin = require('gulp-imagemin')
// File reference processing, compression merge
const useref = require('gulp-useref')
// Conditional plugins
const ifPlugin = require('gulp-if')
// File compression
const htmlmin = require('gulp-htmlmin')
const uglify = require('gulp-uglify')

// Create a development server
const browserSync = require('browser-sync')
const bs = browserSync.create()

function serve() {
    watch('./src/assets/styles/*.css', cssStyle)
    watch('./src/assets/styles/*.scss', sassStyle)
    watch('./src/**/*.js', js)
    watch('./src/**/*.html', page)
    // watch('./src/assets/images/**', image) 
    // watch('./src/assets/fonts/**', font)
    // watch('public/**', extra)

    // To minimize the number of builds, set the Settings to listen for images, fonts, public files, notify the browser when changes occur, and trigger bs.reload to retrieve the latest file
    watch([
        'src/assets/images/**'.'src/assets/fonts/**'.'public/**'
    ], bs.reload)

    bs.init({
        port: 2000./ / port
        files: 'dist/**'.// Dist file changes are automatically notified to the browser, and implementation source code changes are automatically synchronized to the browser
        server: {
            // Improve build efficiency: To start the development server, you need to find temp first. Temp is the packaged HTML, CSS, js
            baseDir: ['temp'.'src'.'public'].routes: {
                '/node_modules': 'node_modules'}}})}// Clear the formal environment directory dist, temporary directory/temp temp compilation intermediate directory (development environment build files in temporary directory temp)
function clean () {
    return del(['dist'.'temp'])}function cssStyle() {
  return src('./src/assets/styles/*.css', { base: 'src' })
  .pipe(cleanCss())
  .pipe(rename({ extname: ".min.css" }))
  .pipe(dest('temp'))}// _. SCSS files will default to mian. CSS dependencies and will be packaged in the mian
function sassStyle() {
  return src('./src/assets/styles/*.scss', { base: 'src' })
  .pipe(sass({ outputStyle: 'expanded' })) // Set the output style to fully expand
  .pipe(cleanCss())
  .pipe(rename({ extname: ".min.css" }))
  .pipe(dest('temp'))}function js() {
  return src('./src/**/*.js', { base: 'src' })
  .pipe(babel({ presets: ['@babel/preset-env']}))// Babel is just an ES conversion platform, preset is not a conversion itself, just provides an environment, the conversion is implemented by some internal plug-ins, preset is a collection of plug-ins
  .pipe(dest('temp'))}// Swig ({data}) is used in the HTML template
const data = {
    pkg: {
        name: 'lili'.description: 'First automated build'}}function page() {
  return src('./src/**/*.html', { base: 'src' })
  .pipe(swig({data}))
  .pipe(dest('temp'))}// Lossless compression, just delete some image information
function image() {
  return src('./src/assets/images/**', { base: 'src' })
  .pipe(imagemin())
  .pipe(dest('dist'))}// Font files also use imagemin plugin, can compress inside SVG image, other font files do not handle direct output by default
function font() {
  return src('./src/assets/fonts/**', { base: 'src' })
  .pipe(imagemin())
  .pipe(dest('dist'))}// Make copies of additional static files - only needed when deploying formal environment packaging
function extra() {
  return src('public/**', { base: 'public' })
  .pipe(dest('dist/public'))}function userefTask() {
    return src('temp/*.html', { base: 'temp' })
    .pipe(useref({ searchPath: ['temp'.'. ']}))// Convert build comments in code
    .pipe(ifPlugin(/\.js$/, uglify()))
    .pipe(ifPlugin(/\.css$/, cleanCss()))
    .pipe(ifPlugin(/\.html$/, htmlmin(
        {
        // Compress HTML inline JS and CSS
        collapseWhitespace: true.minifyCSS: true.minifyJS: true
    }
    )))
    .pipe(dest('temp'))}const complicate = parallel(sassStyle, cssStyle, js, page)

const build = series(clean, parallel(series(complicate, userefTask), image, font, extra))
const dev = series(complicate, serve)

module.exports = {
  clean,
  build,
  dev
};
Copy the code

Automatically loads all gulp plug-ins

In the gulpfile.js file, we can’t avoid introducing various gulp plug-ins, so we need to write a lot of repetitive import code. Here, we can use gulp-load-plugins to automatically load all gulp plug-ins at once. Also run the command line from the terminal to install the development dependency.

const loadPlugins = require('gulp-load-plugins')
const plugins = loadPlugins()
Copy the code

All of the places above where the gulp plug-in is used can be optimized as shown in the following example: cleanCss() is changed to plugins.cleancss (), which omits the code introduced separately from the plug-in

function cssStyle() {
  return src('./src/assets/styles/*.css', { base: 'src' })
  .pipe(plugins.cleanCss())
  .pipe(dest('dist'))}Copy the code

Configure package.json for collaborative development and use

The exposed tasks are configured under the scripts option in package.json. This allows our terminal to perform gulP tasks using shortcuts. For example, yarn Clean, yarn Build, and yarn Start

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

Encapsulating workflow

Extract the data

  • The data above should not be stored in gulpfile.js. You need to extract the data into a file and import it using require
  • Provides configurable capabilities such as write dead absolute paths'./src/assets/images/**'Abstract to be configurable

Creation is not easy, please move your finger and point a thumbs-up, welcome to leave a message to me ~~~