gulp front-end automation build tool: introduction and use of common plug-ins

Keywords: Javascript less sass npm

Gulp is a building tool based on Node.js (automatic task runner), which can be used by developers to build automated workflow (front-end integrated development environment). Some common and repetitive tasks, such as automatic page refresh, CSS preprocessing, code detection, compressed pictures, etc. All this can be done with a simple command. By using it, you can simplify your work and focus on functional development; at the same time, reduce human errors, improve development efficiency and project quality, and make your focus more focused. If you've been exposed to Grunt before, Gulp will find it very easy to understand.

_github address: https://github.com/San-Shui/gulp

_gulp plug-in: https://gulpjs.com/plugins/

_This project uses gulp-web server to create a static server, gulp-live reload to automatically refresh web pages, and introduces the common plug-ins and the use of plug-ins.

  • Local installation

To install the latest version or a specific version, run one of the following commands:

npm install –save-dev gulp

  • Global installation

The following NPM installation methods will make gulp available in a global environment:

npm install –global gulp

clone remote warehouse to local:

git clone https://github.com/San-Shui/gulp.git

Enter gulp directory

cd gulp

Installation dependency

yarn install or npm install

Operation item

gulp

gulp configuration file:

var gulp = require('gulp')
// Web page automatic refresh (server control client synchronous refresh)
var livereload = require('gulp-livereload')
// Local Server
var webserver = require('gulp-webserver')
// less file compiled into css
var less = require('gulp-less') 
// Compression of css files
var cssmin = require('gulp-clean-css')
// Generate sourcemap files
var sourcemaps = require('gulp-sourcemaps')
// Indicate an error when an exception occurs
var notify = require('gulp-notify')
var plumber = require('gulp-plumber')
// Compressing html can compress pages javascript, css, remove page spaces, annotations, delete redundant attributes and other operations
var htmlmin = require('gulp-htmlmin')
// Operate only files that have been modified
var changed = require('gulp-changed')
// Compressed image files (including PNG, JPEG, GIF and SVG images)
var imagemin = require('gulp-imagemin')
// Deep Compressed Pictures
var pngquant = require('imagemin-pngquant')
// Compress only the modified image, and read the unmodified image directly from the cache file (C: Users Administrator AppData Local Temp gulp-cache).
var cache = require('gulp-cache')
// Add a version number to the reference url in the css file
var cssver = require('gulp-make-css-url-version')
// Compress javascript files to reduce file size
var uglify = require('gulp-uglify')
// File renaming
var rename = require('gulp-rename')         
// Merge javascript files to reduce network requests
var concat = require('gulp-concat')
// file cleanup
var clean = require('gulp-clean')               

// Compile to css using gulp-less file
gulp.task('lessTask', function() {
    gulp.src('src/less/*.less')
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')})) // Error prompt
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(rename({ suffix: '.min' })) // rename
        .pipe(less()) // Compile less file to css
        .pipe(cssmin()) // Compress css
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('dist/css')) // index.css and detail.css will be generated under dist/css
})

// watch Monitoring changes in less files
gulp.task('lessWatch', function () {
    gulp.watch('src/**/*.less', ['lessTask']); // Call the lessTask task when a less file under the src file or subfile changes
});

// Compressing html with gulp-htmlmin
gulp.task('htmlminTask', function () {
    var options = {
        removeComments: true, // Clear HTML comments
        collapseWhitespace: true, // Compress HTML
        collapseBooleanAttributes: true, // The value of the omitted Boolean attribute is <input checked="true"/>==> <input/>.
        removeEmptyAttributes: true, // Delete all spaces as attribute value <input id="/>==> <input/>.
        removeScriptTypeAttributes: true, // Delete the type of <script>= "text/javascript"
        removeStyleLinkTypeAttributes: true, // Delete the type of <style> and <link>= "text/css"
        minifyJS: true, // Compressed page JS
        minifyCSS: true // Compressed page CSS
    };
    var stream = gulp.src('src/*.html')
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')})) // Error prompt
        .pipe(changed('dist'))
        .pipe(htmlmin(options))
        .pipe(gulp.dest('dist'))
    return stream

})

// Compressing pictures using gulp-imagemin
gulp.task('imageminTask', function () {
    var option = {
        optimizationLevel: 5, //Type: Number default: 3 value range: 0-7 (optimization level)
        progressive: false, //Type: Boolean default: false lossless compression jpg images
        interlaced: false, //Type: Boolean default: false interlaced gif for rendering
        multipass: false //Type: Boolean default: false optimizes svg several times until it is fully optimized
    }
    gulp.src('src/img/*.{png,jpg,gif,ico}')
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')})) // Error prompt
        .pipe(imagemin(option))
        .pipe(gulp.dest('dist/img'))
})

// Deep compression of images using imagemin-pngquant
gulp.task('pngquantTask', function () {
    gulp.src('src/img/*.{png,jpg,gif,ico}')
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')})) // Error prompt
        .pipe(changed('dist/img'))
        .pipe(imagemin({
            progressive: true,// Lossless Compression of JPG Pictures
            svgoPlugins: [{removeViewBox: false}],//Do not remove the viewbox attribute of svg
            use: [pngquant()] // UsepngquantDeep compressionpngPictureimageminPlug-in unit
        }))
        .pipe(gulp.dest('dist/img'));
})

// Use gulp-cache to compress only modified images
gulp.task('cacheTask', function () {
    gulp.src('src/img/*.{png,jpg,gif,ico}')
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')})) // Error prompt
        .pipe(changed('dist/img'))
        .pipe(cache(imagemin({
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        })))
        .pipe(gulp.dest('dist/img'));
})

// Compressing CSS files with gulp-clean-css
gulp.task('cssminTask', function() {
    var option = {
        advanced: true,//Type: Boolean default: true [whether to turn on advanced optimization (merge selectors, etc.)]
        compatibility: 'ie7',//Keep IE7 and the following compatible writing types: String default:''or'*'[Enable compatible mode;'ie7': IE7 compatible mode,'ie8': IE8 compatible mode,'*': IE9 + compatible mode]
        keepBreaks: false,//Type: Boolean default: false [reserve newline]
        keepSpecialComments: '*'//Keep all special prefixes when you use the browser prefix generated by autoprefixer. If you don't add this parameter, you may delete some of your prefixes.
    }
    gulp.src('src/css/*.css')
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')})) // Error prompt
        .pipe(cssmin(option)) // Compress css
        .pipe(gulp.dest('dist/css')) // index.css and detail.css will be generated under dist/css
})

// Use gulp-make-css-url-version to add a version number to the reference URL in the CSS file
gulp.task('cssverTask', function () {
    gulp.src('src/css/*.css')
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')})) // Error prompt
        .pipe(sourcemaps.init()) // Execute sourcemaps
        .pipe(rename({ suffix: '.min' })) // rename
        .pipe(cssver()) //Add a version number to the reference file in the css file (file MD5)
        .pipe(cssmin())
        .pipe(sourcemaps.write('./')) // Map Output Path (Storage Location)
        .pipe(gulp.dest('dist/css'));
})

// Use gulp-uglify to compress javascript files and reduce file size.
gulp.task('uglifyTask', function () {
    gulp.src(['src/js/*.js', '!src/js/**/scrollspy.js'])
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')})) // Error prompt
        .pipe(changed('dist/js')) // Corresponding matching files
        .pipe(sourcemaps.init()) // Execute sourcemaps
        .pipe(rename({ suffix: '.min' })) // rename
        .pipe(uglify()) // Use uglify to compress and keep some comments
        .pipe(sourcemaps.write('./')) // Map Output Path (Storage Location)
        .pipe(gulp.dest('dist/js'));
});

// Use gulp-concat to merge javascript files to reduce network requests.
gulp.task('concatTask', function () {
    gulp.src(['dist/js/*.js'])
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')})) // Error prompt
        .pipe(concat('concatLibs.js')) // Merge into libs.js
        .pipe(rename({ suffix: '.min' })) // rename
        .pipe(gulp.dest('dist/js'))
})

// File replication
gulp.task('copyTask', function () {
    gulp.src('src/fonts/*')
        .pipe(gulp.dest('dist/fonts'))
})

// Clean up files
gulp.task('cleanTask', function() {
    var stream = gulp.src( 'dist', {read: false} ) // Clean up maps files
        .pipe(clean())
    return stream
})

// Registration task
gulp.task('webserver', ['htmlminTask'], function() {
    gulp.src( 'dist' ) // Server directory (. / Represents root directory)
    .pipe(webserver({ // Running gulp-webserver
      livereload: true, // Enable LiveReload
      open: 'index.html', // Open Web Page Automatically when Server Starts
      port: 8089 // Service port
    }))
})

// Monitoring task
gulp.task('watch', function(){
    // Monitoring less
    gulp.watch( 'src/less/*.less' , ['lessTask'])
    // Monitoring html
    gulp.watch( 'src/*.html' , ['htmlminTask'])
    // Monitor images
    gulp.watch( 'src/img/*.{png,jpg,gif,ico}' , ['pngquantTask'])
    // Monitoring js
    gulp.watch( ['src/js/*.js','!src/js/*.min.js'] , ['uglifyTask'])
    // Monitoring css
    gulp.watch( 'src/css/*.css' , ['cssverTask'])
})

// Default task
gulp.task('default',[ 'htmlminTask', 'copyTask', 'cssverTask', 'uglifyTask', 'cacheTask', 'lessTask', 'webserver', 'watch'])

After running, a dist directory is generated, and the files in the dist directory are automatically generated by configuring gulp.

Modifying any file in the src directory automatically refreshes the page

Plug-in summary

1. Compile

  • gulp-sass - Compiles Sass into CSS through libsass
  • gulp-ruby-sass - Compiles Sass into CSS via Ruby Sass
  • gulp-compass - Compiled to CSS via Ruby Sass and Compass Sass
  • Gulp-less-Less is compiled into CSS.
  • Gulp-stylus-Stylus is compiled into CSS.
  • Gulp-postcss-Pipe CSS through PostCSS processors with a single parse.
  • Gulp-coffee-Coffeescript is compiled into JavaScript.
  • Gulp-typescript-TypeScript is compiled into JavaScript.
  • Gulp-react-Facebook React JSX template is compiled into JavaScript.
  • webpack-stream - Integrates webpack into Gulp.
  • Gulp-babel-ES6 is compiled into ES5 via babel.
  • Gulp-traceur-ES6 is compiled into ES5 via Traceur.
  • Gulp-regenerator-ES6 is compiled into ES5 through Regenerator.
  • gulp-es6-transpiler - [outdated] ES6 is compiled into ES5 via es6-transpiler.
  • gulp-myth - Myth - a polyfill for future versions of the CSS spec.
  • gulp-cssnext - [obsolete] uses the next generation of CSS specifications to pass cssnext.

2. Merger

  • gulp-concat-Merge files.
  • -

3, compression

  • gulp-clean-css-Compressed CSS through clean-css.
  • gulp-csso-Compressed CSS through CSSO.
  • gulp-uglify-Compressed JavaScript via Uglify JS2.
  • gulp-htmlmin-Compressed HTML via html-minifier.
  • gulp-minify-html-Compressed HTML via Minimize.
  • gulp-imagemin-Compressed PNG, JPEG, GIF and SVG images via imagemin.
  • gulp-svgmin - Compressing SVG files through Gulp

4, optimization

  • gulp-uncss - Removes unused CSS selectors via UnCSS.
  • gulp-css-base64 - Converts all resources in a CSS file (declared by url() into URI strings of base64-encoded data
  • gulp-svg2png - Converting SVGs to PNGs
  • Gulp-response - Generate pictures of different sizes
  • gulp-svgstore - Merges svg files into a passing element
  • gulp-iconfont - Create icon fonts through SVG icons

5. Resource injection

  • gulp-useref - parses script or style tags in special tags in HTML files, merges them into a script or css file, and replaces them.
  • gulp-inject - Insert the specified css or js file as a tag into the specified flag in HTML.
  • Widep - Automatically injects Bower dependencies into HTML files.

6, template

  • Gulp-angular-template ache-Contact and register Angular JS template in $template Cache
  • Gulp-jade-Jade converts to HTML.
  • Gulp-handlebars-Handlebars template converted to JavaScript.
  • Gulp-hb-Handlebars template converted to HTML.
  • Gulp-nunjucks-Nunjucks template converted to JavaScript.
  • Gulp-dustjs-Dust template converted to JavaScript.
  • Gulp-riot-Riot template converted to JavaScript.
  • gulp-markdown - Markdown → HTML.
  • Gulp-template-Lodash template converted to JavaScript.
  • Gulp-swig-Swig template is converted to HTML.
  • Gulp plugin for [remark]( https://github.com/wooorm/remark ) Processing markdown through plug-ins

7. Code Verification

  • gulp-csslint-Check CSS automatically through CSSLint.
  • gulp-htmlhint - Verify HTML by HTMLHint.
  • gulp-jshint-Find errors and potential problems through JSHint.
  • gulp-jscs-Check JavaScript code style through jscs.
  • gulp-coffeelint - A check used to ensure a uniform style of CoffeeScript code.
  • TypeScript Code Verification Plug-in for gulp-tslint-gulp.
  • Gulp-eslint-ECMAScript/JavaScript code validation.
  • gulp-w3cjs-Tests HTML through w3cjs.
  • gulp-lesshint-Check LESS through lesshint.

8. Real-time loading

  • browser-sync - Ensure multiple browser or device pages to be displayed synchronously (recipes).
  • Gulp-live reload-Gulp real-time load plug-in.

9, cache

  • gulp-changed - Allows only files that have changed to pass.
  • gulp-cached-a simple file memory cache.
  • gulp-remember-Memorize and recycle the passed documents.
  • gulp-newer - Only new source code is allowed to pass.

10. Flow control

  • merge-stream - Merge multiple streams into one insert stream.
  • streamqueue - The stream that gradually enters the queue.
  • run-sequence - Run some dependent Gulptask as required.
  • gulp-if - Run task according to conditions.

11, log

  • Gulp-notify-Gulp notification plug-in.
  • gulp-size - Displays the size of your project.
  • gulp-debug - Observe which files pass through your Gulp pipeline by debugging the file stream.

12, test

  • gulp-mocha - Run Mocha test cases.
  • gulp-jasmine-Run the Jasmine 2 test case in Node.js.
  • gulp-protractor-wraps Gulp for Protractor test cases.
  • gulp-coverage - Covers independent reports for Node.js relative to running test runs.
  • gulp-karma-Run Karma test cases through Gulp.
  • gulp-ava-Runs AVA test cases through Gulp.

13. Other plug-ins

  • gulp-util - contains a series of useful plug-ins.
  • Gulp-plus - Prevent pipe breaking caused by errors caused by errors caused by errors.
  • gulp-load-plugins-Autoload Gulp plug-ins.
  • main-bower-files-automatically retrieve the files of the bower library at build time.
  • autoprefixer - Parses CSS and adds browser compatibility prefixes according to rules.
  • gulp-sourcemaps-Provides source map support.
  • A string replacement plug-in for gulp-replace-Gulp.
  • gulp-rename-Easily rename files.
  • gulp-rev - Add a hash value after the static file name, such as unicorn.css_unicorn-d41d8cd98f.css.
  • del - Delete files/folders using globs.
  • gulp-exec - Run a shell command.
  • gulp-strip-debug-Remove console,alert,debugger declarations from javascript code.
  • gulp-cssimport-parse the CSS file, find the imports, and replace the connection file with the imort declaration.
  • gulp-inline-css - Puts the CSS attribute in HTML into the style tag.
  • gulp-gh-pages - Publish content to GiHub pages.
  • gulp-ng-annotate-Add Angular dependency injection through ng-annotate.
  • gulp-bump - Any semvar JSON version via Gulp Bump.
  • gulp-file-include-through Gulp Include file.
  • gulp-zip - Compresses files in ZIP format.
  • gulp-git - Run the GIT command through Gulp.
  • gulp-filter - Use globbing to filter files.
  • gulp-preprocess-Configure preprocessing files based on custom content or environment.

    Reference link: http://www.cnblogs.com/-ding/p/5972162.html

Posted by mattmate on Fri, 24 May 2019 14:51:32 -0700