Gulp is an automated build tool that allows developers to automate common tasks. Here is a brief introduction to how to use GULP to achieve front-end engineering automation using a previous demo I made.

The project structure

SRC directory represents the source code of the project, including less, JS, HTML, etc., while dist directory stores the code generated after gulP compilation, which is equivalent to the production environment. Last and most important is gulpfile.js, which is used to set up gulp-related configurations, similar to webpack.config.js in webpack.

The installation

Gulp.js – The Streaming Build System gulp.js – The streaming Build system

3.9.1 The installation is as follows:

npm install --save-dev gulp
Copy the code
grammar
  • gulp.task()Used to define agulpTask, available from the command lineGulp [task name]Enable the task.
  • gulp.src()Returns a file stream that matches the file stream that can bepipe()Into other plug-ins.
  • gulp.dest(): Outputs all data.
  • gulp.watch()Used to monitor changes to documents.
practice

In this project, there are some common requirements, which are automated using GULP:

  • Turn less CSS
  • CSS compression merge
  • Js compression merge
  • Image compression

In gulpfile.js, you need to import gulp and some common plug-ins. The plug-ins used in this demo are as follows:

Var gulp = require('gulp'), less = require('gulp'), less = require('gulp-less'), Uglify = require('gulp-uglify'); //js = require('gulp-jshint'), //js = require('gulp-jshint') Imagemin = require('gulp-imagemin'), rev = require('gulp-rev'), RevReplace = require('gulp-rev-replace'), // useref = require('gulp-useref'), Gulpif = require('gulp-if'), //if connect = require('gulp-connect'); // Create web serverCopy the code
Image compression

Get all the images ending in.jpg or.png under SRC and compress them to the dist directory.

gulp.task('dist:img', () => {
    gulp.src(['./src/**/*.jpg', './src/**/*.png'])
    .pipe(imagemin())
    .pipe(gulp.dest('dist/'))
})
Copy the code
Less compression is merged into CSS

Delete the existing CSS, and convert the files ending in. Less under SRC into CSS files through less(). Then use csso() and concat() to compress and merge the CSS.

gulp.task('dist:css', () => {
    gulp.src('dist/css/*.css').pipe(clean());
    return gulp.src('./src/less/*.less')
    .pipe(less())
    .pipe(csso())
    .pipe(concat('public.css'))
    .pipe(gulp.dest('dist/css/'));
});
Copy the code
Js compression merge

The js compression merge process is much the same, with the addition of a jshint() code review process, which prints non-conforming error code to the console.

gulp.task('dist:js', () => {
    gulp.src('dist/js/*.js').pipe(clean());
    return gulp.src('./src/js/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(uglify())
    .pipe(concat('public.js'))
    .pipe(gulp.dest('dist/js/'))
});
Copy the code
Turn less CSS

During development, because HTML cannot be imported directly into.less files, you also need to generate.CSS for your development environment.

gulp.task('src:css', () => {
    gulp.src('src/css/*.css').pipe(clean());
    return gulp.src('./src/less/*.less')
    .pipe(less())
    .pipe(gulp.dest('src/css/'));
});
Copy the code
Add version number

To prevent the browser from caching files, you need to add a version number to the file to ensure that the latest code is retrieved each time.

gulp.task('revision', ['dist:css', 'dist:js'], () => {
    return gulp.src(["dist/css/*.css", "dist/js/*.js"])
    .pipe(rev())
    .pipe(gulpif('*.css', gulp.dest('dist/css'), gulp.dest('dist/js')))
    .pipe(rev.manifest())
    .pipe(gulp.dest('dist'))
})
gulp.task('build', ['dist:img'], () => {
    var manifest = gulp.src('dist/rev-manifest.json');
    return gulp.src('src/index.html')
    .pipe(revReplace({
        manifest: manifest
    }))
    .pipe(useref())
    .pipe(gulp.dest('dist/'))
})
Copy the code

In revision, rev() generates a file with a version number on the.css/.js file in the dist directory, such as public-5C001C53f6.css in this example, and outputs the file to different directories. Finally, generate a rev-manifest.json file, which stores the mapping between the original file and the file with the version number, as follows:

{
  "public.css": "public-5c001c53f6.css",
  "public.js": "public-93c275a836.js"
}
Copy the code

Json. Use revReplace() to replace the version number. Use useref() to parse and locate the resource.

Take the introduction of JS files as an example, the introduction of files in the source HTML file should be rewritten in the following form, that is, the path of files generated after construction should be written in the form of comments, as follows:

<! - build: js. / js/public. Js - > < script SRC = ".. / js/jquery - 1.12.4. Min. Js "> < / script > < script SRC =". / js/myAlbum. Js "> < / script > <! -- endbuild -->Copy the code

The resulting HTML is:

<script src="./js/public-93c275a836.js"></script>
Copy the code

For details, see gulp-useref.

Create a local server and implement an automatic refresh

Use connet.server() to create a local server, use gulp.watch() to monitor the files under SRC, and compile less to CSS and refresh the page if changes are made.

gulp.task('connect', () => {
    connect.server({
        root: 'src',
        livereload: true,
        port: 8888
    })
})
gulp.task('reload', () => {
    gulp.src('src/*.html')
    .pipe(connect.reload())
})
gulp.task('watch', () => {
    gulp.watch('src/**/*', ['src:css', 'reload'])
})
Copy the code

The full code can be found on Github.

Original address:

  • Use GULP for front-end automation