preface

A few days ago, the company needed to reconstruct an old version of the project. Actually, it is not old. A desktop application project developed in June last year was mainly designed to make compatible hardware devices, not browsers (such as navigation screens in cars). I wrote a version using Vue, but the hardware does not support Vue, so I used JQuery1 with Bootstrap and Gulp for hot update and packaging.


Application scenarios

Gulp is a simple and fast build tool based on Node stream. Last time I talked to my colleague about the rapid iteration of the front end, he said that the front end was being updated for the sake of updating (making some unnecessary updates). In fact, some of the older methods are also more convenient for some projects, although the main popular webpack, when dealing with simple HTML, CSS, JS, etc., the front and back end of the project, I think gulp is good.

The installation of a gulp

3.9.0 (4.0.0 will give an error, as if the command had changed)

NPM I -g gulp NPM init NPM I -d [email protected]Copy the code

The use of gulp

If our project structure is like this, create a new gulpfile.js file and use it as the entry point to build the project



The target structure looks like this

  1. Package all CSS files under the CSS file as index.min.css
  2. Package all less files under the less file as main.min.css
  3. Reenergize all third party introduced CSS under extend file
  4. Package all js files under the js file as main.min.js

So how do you do that with gulp?

This is a gulp plugin for pageage.json (there are many plugins out there, I’m just citing a litchi)

 "devDependencies": {   
     "gulp": "^ 3.9.0"."gulp-concat": "^ 2.6.1." "."gulp-connect": "^ 5.7.0"."gulp-htmlmin": "^ 5.0.1." "."gulp-imagemin": "^ 5.0.3." "."gulp-less": "^ 4.0.1." "."gulp-minify-css": "^ 1"."gulp-uglify": "^ 3.0.2." " 
 }Copy the code

In gulpfile we reference them

    var gulp =require("gulp");
    var connect = require('gulp-connect'); Var concat=require('gulp-concat'); Var less = require('gulp-less'); Var jsuglify = require('gulp-uglify'); Var cssminify = require('gulp-minify-css'); // Compress CSS var imageMin = require('gulp-imagemin'); // img var htmlmin = require('gulp-htmlmin'); HTML / / compressionCopy the code

Begin to build

Gulp’s official API

    gulp.task("Task Name".function(){          })
    gulp.src('road king'// readable stream.pipe (gulp.dest('Target road strength') // Pipe --> writable streamCopy the code

  • Start a port for a hot update preview

// Service, port gulp.task("server".function(){
        connect.server({ 
           root:"dist"Livereload, / / path:true,
            port:8080 
       })  
  })Copy the code
  • Hot updates listen for changes to any files under SRC

// Hot update gulp.task("reload".function(){
   gulp.src("./src/**/*.*") 
   .pipe(connect.reload());
})Copy the code

  • Dev mode and Build mode
  • Listen for SRC file changes, perform build task to update dist file, and perform reload reset browser for hot update

 gulp.task("watch".function(){ 
   gulp.watch("./src/**/*.*"["build"."reload"]); // listen on all files under SRC}) gulp.task("dev"["server".'watch'].function() {/ /functionYou can skip console.log("dev")})Copy the code

  • Package to generate dist files

gulp.task("build"['html'.'css'.'extendcss'.'less'.'js'.'image'[] // Perform the following tasks for packagingCopy the code

In the build task, we performed ‘HTML ‘,’ CSS ‘,’ ExtendCSS ‘,’less’,’js’,’image’, etc

Establish a task

//   css
gulp.task("css".function(){
    gulp.src("./src/css/*.css"// Any CSS file. Pipe (concat('main.min.css')) // Merge files into main.min.css.pipe (cssminify()) // compress css.pipe (gulp.dest()'dist/css') // output to dist/ CSS folder}) // ExtendCSS dependent third party CSS does not do the processing only change the road force gulp.task("extendcss".function(){
    gulp.src("./src/extend/*.css")
    .pipe(gulp.dest('dist/css'))
   })
//   less
gulp.task("less".function(){
    gulp.src("./src/less/*.less".pipe(less()).pipe(concat())'index.min.css'))
    .pipe(cssminify())
    .pipe(gulp.dest('dist/css'))
   })
// js
gulp.task('js'.function() {  
  
gulp.src('./src/js/*.js'// 1. Find file. Pipe (jsuglify({mangle:false}) // 2. Zip file. Pipe (concat()'main.min.js'// 3. Save the compressed file. Pipe (gulp.dest('dist/js'))})
// image
gulp.task('image'.function(){
    gulp.src('src/img/*.*')
        .pipe(imageMin({optimizationLevel: 5, // type: Number Default: 3 Value range: 0-7) Progressive:true, // Type: BooleanfalseLossless compression of JPG pictures interlaced:true, // Type: BooleanfalseInterlaced scan GIF for rendering multipass:true// Type: BooleanfalseOptimize SVG several times until it is fully optimized})).pipe(gulp.dest('dist/img'))})
//  html
gulp.task("html".function(){
     var options = {
        removeComments: true// Clear HTML comment collapseWhitespace:true, / / compress HTML collapseBooleanAttributes:false// omit the value of the Boolean attribute <input checked="true"/> ==> <input />    
        removeEmptyAttributes: false,// remove all Spaces as attribute values <input id="" /> ==> <input /> 
        removeScriptTypeAttributes: true// Delete <script>type="text/javascript"  
        removeStyleLinkTypeAttributes: true// Delete <style> and <link>type="text/css" 
        minifyJS: true// Compress the page JS minifyCSS:true// compress the page CSS}; gulp.src("./src/*.html")
     .pipe(htmlmin(options)) 
     .pipe(gulp.dest('dist'))})Copy the code

run

We perform

gulp dev Copy the code

We can preview the localhost:8080 project in the browser and update it automatically without refreshing the page when we make changes to the file under SRC.

If you don’t like the gulp command, you can modify the JSON command

NPM run build NPM run dev

 "scripts": {   
    "dev": "gulp dev"."build": "gulp build"."test": "echo \"Error: no test specified\" && exit 1" 
 },Copy the code

Write in the back

Really like this kind of similar structure that is simple, short development cycle, don’t need a webpack the cow force build tools, every project has a suitable for their own, as now the front end of the project, no matter what your skin, I am vue, the react a shuttle, ah ha ha ha, vue, jq, suitable for the project is the best, As the old saying goes, how do you know if it’s right until you try it? (Naturally, the company won’t give you the time to try.)

Ha ha, first time to write, slip slip slip.