preface

There are several ways to develop web pages today, using vue-CLI, creation-React-app, Webpack, single-page or multi-page websites without building tools, etc. The first three ways can undoubtedly meet most of our requirements for developing web pages, but in some cases, such as the front and back end without separation (JSP, PHP, TPL and other nested backend languages), and simply develop some static pages (active pages, help manuals, etc.), Building a lightweight front-end development environment using Gulp is an option.

Gulp is relatively easy to get started, and experienced front-end users are familiar with it. Here I will not introduce the construction of gulp development environment step by step, but share the code and ideas of using gulp in practice.

What functions to implement

The goal of using Gulp is to automate builds and improve development efficiency and code quality, so there are some goals.

  1. Compress HTML, CSS, JS, images
  2. Compile ES6, LESS/SCSS
  3. Complete the CSS prefix
  4. Turn the px rem
  5. Static resource cache control
  6. Static server
  7. Code review

There is more that gulp can do, but for the purpose of developing static pages, only some of the common features are listed here.

code

The basic directories are as follows

Gulpfile.js main code

Static server

gulp.task('server', done => {
    connect.server({
        root: 'dist'./ / root directory
        livereload: true.// Automatic update
        port: 9090/ / port
    })
    done();
});
Copy the code

Compressed HTML

gulp.task('html'.function () {
    return gulp.src('src/*.html')
        .pipe(htmlmin({ collapseWhitespace: true }))
        .pipe(gulp.dest('dist'))
        .pipe(connect.reload())
})
Copy the code

Compile and compress CSS

gulp.task('css', done => {
    var processors = [px2rem({ remUnit: 100 })];

    gulp.src('src/less/**/*.less')   // Get the paths of all less files.pipe(less())               / / tiled
        .pipe(autoprefixer({// Complete the prefix
            overrideBrowserslist: [
                "Android 4.1"."iOS 7.1"."Chrome > 31"."ff > 31"."ie >= 8"
            ]
        }))
        .pipe(postcss(processors))//px to REM Tips: If a px is not converted, use uppercase instead, like 1PX
        .pipe(minifyCss())
        .pipe(gulp.dest('dist/css'))
        .pipe(connect.reload())

    done();
});
Copy the code

Compile and compress JS

gulp.task('js'.function () {
    return gulp.src('src/js/**/*.js')
        //.pipe(jshint()
        .pipe(babel({/ / compile ES6
            presets: ['@babel/env']
        }))
        .pipe(uglify())Js / / compression
        .pipe(gulp.dest('dist/js'))
        .pipe(connect.reload())
})
Copy the code

The compressed image

gulp.task('images'.function () {
    return gulp.src('src/images/**/*.+(png|jpg|jpeg|gif|svg)')
        .pipe(imagemin())
        .pipe(gulp.dest('dist/images'))});Copy the code

Monitoring file changes

gulp.task('watcher', done => { // Listen for changes
    gulp.watch('src/*.html', gulp.series('html'));
    gulp.watch('src/less/**/*.less', gulp.series('css'));
    gulp.watch('src/js/**/*.js', gulp.series('js'));
    gulp.watch('src/images/**/*', gulp.series('images'));

    done();
})
Copy the code

Generates a hash file name and path

Gulp-rev-delete-original is also used to delete old files.

gulp.task("hash", done => {
    gulp
        .src("dist/**")
        .pipe(
            RevAll.revision({
                dontRenameFile: [/\.html$/]
            })
        )
        .pipe(revdel({
            exclude: function (file) {
                if (/\.html$/.test(file.name)) {
                    return true; //if you want to exclude the file from being deleted
                }
            }
        }))
        .pipe(gulp.dest("dist"))

    done();
});
Copy the code

Gulp command

Open the local server and package the file.

/ / initialization
gulp.task('init', gulp.series('clean', gulp.parallel('html'.'css'.'js'.'images')));
/ / development
gulp.task('default', gulp.series('init'.'server'.'watcher'));
/ / packaging
gulp.task('build', gulp.series('hash'));
Copy the code

As you can see, the above code is relatively simple, because it is intended to do simple static pages, so it is not complicated. It monitors the file changes and compiles to the dist directory, and then generates the hash file name from gulp-rev-all.

The condition where the front and back ends do not separate

It is important to distinguish between scenarios where the front and back ends are not separated because the company does not upgrade its technology or needs to maintain old projects. For example, if the page is a JSP or PHP file, there is no direct mapping between the static page and the actual page. Gulp-rev-all will generate a hash file and path after each gulp package, and does not support test.css? V =123, it is not practical to manually copy everything to the project directory, just drop gulp-rev-all(build) and remove code compression.

It is worth mentioning that the backend language can be used for cache control of resources, such as using the modification date of the file read by PHP to make the version number.

function autoVersion($file) {  
    if( file_exists($_SERVER['DOCUMENT_ROOT'].$file) ) {  
        $ver = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);  
    } else {  
        $ver = 1;  
    }  
    return $file .'? v=' .$ver;  
}  
Copy the code
<link rel="stylesheet" href="
       "> <! -- main.css? v=13579 -->
Copy the code

In addition, there should be a solution to not separating the front end from the back end by directly generating the template files (such as index.tpl) required by the back end with the help of a build tool, which is not discussed here.

The last

This is based on work experience, and while single-page development using or based on Webpack is currently the norm, it is necessary to comb through some of the scenarios that are not covered.

Source address: gulp-util, in addition to attach a webpack multi-page scaffolding webpack-multiple-entry, this is the author fork others project to modify, relatively simple and practical, interested partners can refer to the next.