This is the 4th day of my participation in the August More Text Challenge

Gulp and NPM scripts

Gulp and NPM scripts can be built automatically

Gulp has a simple syntax

  • Gulp syntax is JavaScript syntax
  • NPM scripts syntax is similar to shell scripts
    • (example: minify output.css > output.min.css)

Gulp has perfect ecology and high construction efficiency

Gulp is used for basic purposes

steps

  • NPM install -g Gulp -cli

  • Initialize the project NPM init –yes

    • A package.json file appears
  • NPM install Gulp -d

  • Create gulpfile gulpfile.js

  • In gulpfile.js, create a gulp task

    • Demo code (gulpfile.js)
          // Create a Gulp task
        const task1 = () = > {
            console.log("task1 is running");
        }
        const task2 = () = > {
            console.log("task2 is running");
        }
      
        // Expose the task
        module.exports = {
            task1,
            task2
        }
      Copy the code
  • Executing gulp task gulp

    • demo

        // Execute the task
        gulp task1
        // Console error after successful execution
        //The following tasks did not complete: task1
        //Did you forget to signal async completion?
        // Did you forget to send an asynchronous completion signal?
      Copy the code
    • The solution to the error: Pass a callback function to the task

        // The modified code
        const task1 = (cd) = > {
        console.log("task1 is running");
        cd();
        }
        //[14:38:31] Starting 'task1'...
        //task1 is running
        //[14:38:31] Finished 'task1' after 2.44 ms
      Copy the code

Default Default task

  • When a task is named default, you can enter gulp only and omit the task name
  • Demo code
// Create a Gulp task
const task1 = (cd) = > {
    console.log("task1 is running");
    cd();
}
const task2 = (cd) = > {
    console.log("task2 is running");
    cd();
}

// Expose the task
module.exports = {
    task1,
    default:task2
}

// Run Gulp
// Output the result
// Starting 'default'...
// task2 is running
// Finished 'default' after 2.69ms
Copy the code

Old Gulp task declaration

  • Demo code
// Import Gulp package
const gulp = require('gulp');

// Create Gulp task
gulp.task('task3'.(cd) = > {
    console.log('task3 is running');
    cd();
});
// Do not export the task

// Execute the command
gulp taske3
Copy the code
  • conclusion
    • Older versions do not export tasks, but introduce gulp packages

Gulp composite task

  • All tasks in the new version are executed asynchronously
  • Asynchronously executed are: the promise stream callback function in ES6

Gulp task and NPM scripts command

  • Gulp tasks and NPM scripts are executed in the same way

Gulp combined tasks in detail

  • Parallel: gulp. The parallel (task1, task2, task3)
  • Serial: gulp. Series (task1, task2, task3)
  • Gulp task common code structure
// Import gulp package
const gulp = require('gulp');

// Create a task
const task1 = (cd) = > {
    setTimeout(() = > {
        console.log('task1 is running');
    },1000);
    cd();
}
const task2 = (cd) = > {
    setTimeout(() = > {
        console.log('task2 is running');
    },1000);
    cd();
}
const task3 = (cd) = > {
    setTimeout(() = > {
        console.log('task3 is running');
    },1000);
    cd();
}
Copy the code

serial

  • Code demo
/ / serial
exports.s = gulp.series(task1,task2,task3);
Copy the code
  • The execution result

Parallelism (can improve efficiency)

  • Code demo
// Export tasks
/ / parallel
exports.p = gulp.parallel(task1,task2,task3);
Copy the code
  • The execution result

Gulp builds composite tasks

  • gulp.series(task1,gulp.parallel(task2,task3),task4);

Gulp file operation

Review file operations

  • Buffer mode: Source file -> Memory Buffer -> Target file
    • Disadvantages: The buffer area needs to be large enough. If the source file cannot be saved at one time, the file operation will fail.
  • Flow way
    • A large file is cut into small pieces, each of which has a code, and finally spliced back together at the destination in numbered order.
    • It is transmitted through pipes and executed asynchronously.
  • Gulp’s file operations are stream-based.

Features of Gulp file operations

  • 1. Task-based, all builds are tasks.
  • 2. Stream-based. File operations are stream-based.

Gulp is a stream-based build system

  • Input: Reads the stream
  • Processing: conversion flow
  • Output: Write to the stream

Gulp pipe flow

  • Detailed Gulp file operation diagram

  • Gulp pipe flow

case

  • supplement
    • Dest: destination Indicates the destination
  • Base case: Move the main. CSS file from the SRC folder to the dest folder
// Create a task
const task = (cd) = > {
    // Get the current path and pipe it to the destination
    gulp.src('src/main.css').pipe(gulp.dest('dest'));
    cd();
}
Copy the code
  • As an advanced example (make sure the structure of the transferred files is the same) : Move the main. CSS file from the styles folder in the SRC folder to the Styles folder in the Dest folder
  • Demo Code 1
// Create a task
const task = (cd) = > {
    // Get the current path and pipe it to the destination
    gulp.src('src/styles/main.css', {base:'src'}).pipe(gulp.dest('dest'));
    cd();
}
Copy the code
  • Demo code 2 uses the deconstruction method in ES6. Advantage: instead of writing gulp function calls every time, you can use function names directly
// // Import the gulp package
const {src,dest} = require('gulp');

// Create a task
const task = (cd) = > {
    // Get the current path and pipe it to the destination
    src('src/styles/main.css', {base:'src'}).pipe(dest('dest'));
    cd();
}
Copy the code

Gulp builds the style file

  • There are many useful plugins for Gulp, which can be found at gulpjs.com.
  • As you can see on Gulp’s website, many plugins reference npmjs.com, so you can also go to npmjs.com

Gulp and NPM scripts plug-ins

  • The names are not exactly the same
  • Gulp is simpler to use

Gulp build style file steps

Gulp converts less to CSS

  • 1. Introduce plug-ins (search npmjs.com and see how to use them)
  • 2. Import packages
  • 3. Write in pipe
  • Note: Since the flow is inherently asynchronous, there is no need to write callback functions.
  • Demo code: successfully convert main.less file to main.css, and store in the destination folder below
// // Import the gulp package
const {src,dest} = require('gulp');
const less = require('gulp-less');

// Create a task
const task = (cd) = > {
    // Get the current path and pipe it to the destination
    // src('src/styles/main.css',{base:'src'}).pipe(dest('dest'));
    return src('src/styles/main.less')
    .pipe(less())
    .pipe(dest('src/styles'));
}
// Output: The main.less file was successfully converted to main. CSS and stored under the destination folder
Copy the code

Gulp converts, compresses, and renames build style files

  • npm i gulp-less -DConvert less files to CSS files
  • npm i gulp-clean-css -DCompressing CSS Files
  • npm i gulp-rename -DRename the file
  • Demo code
// // Import the gulp package
const {src,dest} = require('gulp');
/ / conversion
const less = require('gulp-less');
/ / compression
const clean = require('gulp-clean-css');
/ / renamed
const rename = require('gulp-rename');

// Create a task
const task = (cd) = > {
    // Get the current path and pipe it to the destination
    // src('src/styles/main.css',{base:'src'}).pipe(dest('dest'));
    return src('src/styles/main.less')
    .pipe(less())
    .pipe(clean())
    .pipe(rename({extname:".min.css"}
    ))
    .pipe(dest('dest'));
}
Copy the code
  • Note: Streams are inherently asynchronous, so there is no need to write callback functions

Hack and Autoprefixer

  • Ensure CSS compatibility

CSS hack

  • The CSS code is incompatible
    • The same CSS code looks different in different browsers.

supplement

  • Any build in Gulp is called a task (like file compression and conversion before) and is essentially a JS function
  • The new version of Gulp has a convention that all Gulp tasks are asynchronous.

The appendix

The callback function

  • You go to a store to buy something and it happens that the item you want is out of stock, so you leave your phone number with the shop assistant. A few days later, the store is available, the shop assistant calls you, then you get the phone call and go to the store to pick up the item. In this example, your phone number is called the callback function, you leave your phone with the store clerk, you trigger a callback event when the store later has stock, the store clerk calls you, you call the callback function, and you go to the store to pick up the item, you respond to the callback event. Is answered