gulp-based front-end automation scheme

Keywords: node.js Javascript Front-end github JSON

Preface

In recent years, front-end technology has developed rapidly, especially the popularization of single-page applications. Componentization, engineering and automation have become the trend of front-end development. webpack has become the mainstream of front-end packaging construction, but some antique projects still exist, there is also the need to optimize, just the company's old projects need to optimize, not to mention gulp practice.

In this article, you need to install node s (self-installing) and have a good understanding of gulp. Gulp script download: https://github.com/youhunwl/gulp Welcome to star.

practice

Create project directory

Initialize the npm dependencies and basic information first, and use the command npm init to return all the time to generate package.json file. You can also download it directly from the upper github warehouse directory.

Your project directory is related to the task path in your gulp script, which is written to match all directories and files. Let me give you a simple example: js files in js/common will also be processed here. If you only want to process files in a specific directory, modify the path in the task.

demo/
├── css/
│   ├── index.css
├── js/
│   ├── common/
│   │       └─ common.js
│   ├── index.js
├── img/
│   ├── logo.png
└── index.html

Installation Dependency

The modules needed to install gulp are listed directly in my package.json file.

{
  "name": "demo",
  "version": "0.0.0",
  "private": true,
  "dependencies": {},
  "devDependencies": {
    "gulp": "^3.9.1",
    "gulp-autoprefixer": "^3.1.1",
    "gulp-cache": "^1.0.2",
    "gulp-clean-css": "^3.10.0",
    "gulp-htmlclean": "^2.7.15",
    "gulp-htmlmin": "^3.0.0",
    "gulp-if": "^2.0.2",
    "gulp-imagemin": "^4.1.0",
    "gulp-minify-css": "^1.2.4",
    "gulp-notify": "^3.0.0",
    "gulp-path": "^3.0.3",
    "gulp-rev-append": "^0.1.8",
    "gulp-sequence": "^0.4.6",
    "gulp-sourcemaps": "^2.6.4",
    "gulp-uglify": "^2.0.0",
    "uglify-js": "^3.3.9"
  }
}

Writing gulp script

Create a new gulpfile.js file and introduce the required modules. Here I write the path in PATHS. Specific about the way to write, you can see the gulp official website api: https://www.gulpjs.com.cn/doc...

gulp-minify-css has been abandoned and replaced by gulp-clean-css, which is reserved here only to tell you that the effect is the same, users are consistent, in order to ensure that the project does not have problems, it is better to use the latest.

'use strict';
var gulp = require('gulp'),
    minifycss = require('gulp-minify-css'),//Compressed css is discarded
    cleancss = require('gulp-clean-css'),//Compress css
    imagemin = require('gulp-imagemin'),//Compress pictures
    autoprefixer = require('gulp-autoprefixer'),//Processing Browser Prefixes
    uglify = require('gulp-uglify'),//Compress js
    sourcemaps = require('gulp-sourcemaps'),//Generating sourcemap
    gulpif = require('gulp-if'),//Conditional judgement
    notify = require('gulp-notify'),//Handling errors
    cache = require('gulp-cache'),//Compress only modified images
    htmlclean = require('gulp-htmlclean'),// Streamlining html
    htmlmin = require('gulp-htmlmin'),//Compress html
    rev = require('gulp-rev-append'),//Add version number
    sequence = require('gulp-sequence'),//Synchronized Task Execution
    PATHS = {
    ROOT: './',
    DEST: './dist/',
    HTML: '**/*.{html,htm}',
    CSS: '**/*.css',
    IMG: '**/*.{png,jpg,gif,ico}',
    JS: '**/*.js'
}

Compression processing css

Here you need to exclude the node_modules folder and generate the constructed directory / dist / and their subdirectories, directly! Just follow the excluded directory.

gulp.task('minify-css', function () {
    return gulp.src([PATHS.CSS,'!./dist/**', '!./node_modules/**'])
     .pipe(sourcemaps.init())
     .pipe(autoprefixer({
        browsers: ['last 10 versions', 'Firefox >= 20', 'Opera >= 36', 'ie >= 9', 'Android >= 4.0', ],
        cascade: true, //Whether to Beautify Format
        remove: false //Whether to delete unnecessary prefixes
    }))
     .pipe(cleancss({
        keepSpecialComments: '*' //Keep all special prefixes
    }))
     .pipe(sourcemaps.write('.'))
     .pipe(gulp.dest(PATHS.DEST))
     .pipe(notify({ message: 'css minify complete' }));
});

Some referenced CSS or JS do not need to be compressed, such as jQuery',Bootstrap, or a corporate public library. min.{css,js} and so on.

Here we use gulp-if to exclude min.css.

var conditionCss = function (f) {
    if (f.path.endsWith('.min.css')) {
        return false;
    }
    return true;
};

Modify the operation of processing css

.pipe(gulpif(conditionCss, cleancss({
    keepSpecialComments: '*' //Keep all special prefixes
})))

Compression processing js

By the same token, exclude min.js, and remember to exclude gulp scripts from processing.

gulp.task('minify-js', function () {
    return gulp.src([PATHS.JS, '!./dist/**', '!./node_modules/**', '!gulpfile.js'])
     .pipe(sourcemaps.init())
     .pipe(gulpif(conditionJs, uglify()))
     .pipe(sourcemaps.write('.'))
     .pipe(gulp.dest(PATHS.DEST))
     .pipe(notify({ message: 'js minify complete' }));
});

Compression processing img

gulp.task('minify-img', function () {
    return gulp.src([PATHS.IMG,'!./dist/**', '!./node_modules/**'])
        .pipe(cache(imagemin()))
        .pipe(gulp.dest(PATHS.DEST));
});

Compression Processing HTML

gulp.task('minify-html', function () {
    return gulp.src([PATHS.HTML,'!./dist/**', '!./node_modules/**'])
        .pipe(htmlclean())
        .pipe(htmlmin({
        removeComments: true, //Clear HTML comments
        collapseWhitespace: true, //Compress HTML
        minifyJS: true, //Compressed page JS
        minifyCSS: true, //Compressed page CSS
        minifyURLs: true
    }))
        .pipe(gulp.dest(PATHS.DEST));
});

Add version number

gulp.task('rev', function () {
    return gulp.src([PATHS.HTML,'!./dist/**', '!./node_modules/**'])
        .pipe(rev())
        .pipe(gulp.dest(PATHS.DEST));
});

Synchronized task execution

Because all the tasks of gulp are accomplished asynchronously, sometimes we need to execute tasks synchronously, such as compiling less first and compressing the compiled css, then asynchronization will be a problem.

gulp.task('deploy', sequence(['minify-css', 'minify-js'], 'minify-img', 'rev', 'minify-html'));

Perform all gulp tasks

Here we create a task named default to perform the deploy task above.

gulp.task('default', ['deploy'], function (e) {
    console.log("[complete] Please continue to operate");
})

deploy

Enter gulp or gulp default in the terminal to execute the build, and you can see the compressed code in the output directory we set up.

So far, a simple gulp script is almost written, although sparrows are small and full of internal organs. If you have any good suggestions, welcome to exchange.

Posted by Biocide on Fri, 25 Jan 2019 06:24:14 -0800