Preface:

In the past two days, I have done some manual configuration of gulp, and found that gulp is easy to configure and fast to build, which is a good choice in some scenarios. In this paper, I built it from scratch, and finally packaged and published it to the generation environment. In this article, you can get a quick start on Gulp. Github source code is attached at the end of the article. If you need it, you can download it.

Gulp is introduced:

Gulp is a stream-based front-end automatic build tool, together with Grunt and Webpack as three front-end automatic build tools.

1. Install
NPM install --global gulp-cli //2 Create gulp-demo mkdir gulp-demo //3. Go to CD gulp-demo //4. Initialize project NPM initCopy the code
2. Gulpfile. Js is introduced

Create a gulpfile.js file in the root directory of the project. After executing the gulp command, gulp will read the gulpfile.js file, which is the gulp entry file.

If the project size is too large, you can create a gulpfile.js folder in the root directory and create index.js inside the folder. You can introduce different processing modules in index.js.

Unlike previous versions, which used gulp.task to create different tasks, new versions export tasks mainly through exports.xxx

Ex. :
function test(cb) {
 cb()
}

exports.test = test;
Copy the code

Enter the command gulp test on the console

[16:41:29] Using gulpfile F:\gulp\gulpfile.js [16:41:29] Starting 'test'... [16:41:29] Finished 'test' after 1.95msCopy the code

If you change exports.test =test to exports.default=test, you can build directly by typing gulp in the console.

1. Deal with js

Compress JS, create sourcemap, rename JS

Const {SRC, //gulp built-in method dest} = require('gulp'); // rename js file const rename = require('gulp-rename'); const uglify = require('gulp-uglify'); const sourcemaps = require('gulp-sourcemaps'); function javascript() { return src(['src/js/*.js', '!src/js/*.min.js']) //1. Create a stream from SRC //2. Create sourcemap.pipe (sourcemaps.init()) //pipe is a method in gulp // for linking between streams // 3. Pipe (uglify()) //4. Rename and add min.js. pipe(rename({extName: '.min.js'})) //5. Write sourcemap to.pipe(sourcemaps.write('./')) // 6. Pipe (dest('build/js'))} exports.javascript = javascript;Copy the code

Console input instruction gulp javascript

In build/js, two files index.min.js and index.min.js.map are generated

2. Deal with CSS

Compress CSS, create sourcemap, and rename CSS

const { src, dest } = require('gulp'); const minifyCSS = require('gulp-clean-css'); const sourcemaps = require('gulp-sourcemaps'); const autoprefixer = require('gulp-autoprefixer'); function css() { return src('src/css/*.css') //1. Create sourcemap.pipe (sourcemaps.init()) //3. Pipe (autoprefixer()) // 4. Zip css.pipe (minifyCSS()) //5. Write sourcemap.pipe (sourcemaps.write('./')) //6. Pipe (dest('build/ CSS '))} exports.css = CSS;Copy the code

Console input instruction gulp CSS

CSS and index.min.css.map are generated in build/js

3. Manipulate images
const { src, dest } = require('gulp'); const imagemin = require('gulp-imagemin') function image() { return src('src/images/*.*') // 1. Pipe (imagemin({progressive: true})) // 3. Pipe (dest('build/images'))} exports. Image = image;Copy the code

Console input command gulp image

[17:00:07] Using gulpfile F:\gulp-demo\gulpfile.js
[17:00:07] Starting 'image'...
[17:00:19] gulp-imagemin: Minified 3 images (saved 449 kB - 35.5%)
[17:00:19] Finished 'image' after 12 s
Copy the code

You can see the compression scale of the image

4. Deal with less
const { src, dest } = require('gulp'); const gulpLess = require('gulp-less'); const minifyCss = require('gulp-clean-css') const sourcemaps = require('gulp-sourcemaps'); const rename = require('gulp-rename'); function less() { return src('src/less/**.less') //1. Create the input stream //2. create sourcemap.pipe (sourcemaps.init()) //3. turn less to css.pipe (gulpLess()) //4. Compress CSS. Pipe (minifyCss ()) / / 5. Modify the name. The pipe (rename ({extname: '. Min. CSS '})) / / 6. Write sourcemap.pipe (sourcemaps.write('./')) //7. Pipe (dest('build/less'))} exports. Less = less;Copy the code

The console input command gulp less under build/less generates two files index.min. CSS and index.min.css.map

After the introduction, let’s configure gulp in both the development environment and the formal environment

Development environment:

The development environment requires:

  1. CSS browser prefix added
  2. Hot update
  3. Static server startup
Related configurations:
const gulp = require('gulp'); // built-in const {series, parallel, watch, SRC, dest} = require('gulp'); // const autoprefixer = require('gulp-autoprefixer'); const include = require('gulp-file-include'); const clean = require('gulp-clean'); // const less = require('gulp-less'); // browser const browserSync = require('browser-sync').create(); const reload = browserSync.reload; / / source file path const srcPath = {root: 'SRC', HTML: [' SRC / / *. * * HTML ', '. The SRC/include / / *. * * HTML '], images: 'SRC/images / *, CSS: 'src/css/*.css', less: 'src/less/*.less', js: 'src/js/*.js', library: 'src/library/*.js' }; // const distPath = {root: 'dist', HTML: 'dist', images: 'dist/images', CSS: 'dist/ CSS ', less: 'dist/less', js: 'dist/js', library: 'dist/library', manifest: 'dist/**/*.json', }; Function cssDev() {return SRC (srcpath.css). Pipe (autoprefixer({browsers: ['last 2 versions'], cascade: F. false, })) .pipe(dest(distPath.css)) .pipe(reload({ stream: Function lessDev() {return SRC (srcpath.less).pipe(less()). Pipe (autoprefixer({browsers: function lessDev() {return SRC (srcpath.less).pipe(less()). ['last 2 versions'], cascade: false, })) .pipe(dest(distPath.less)) .pipe(reload({ stream: Function jsDev() {return gulp.src(srcpath.js).pipe(dest(distpath.js)).pipe(reload({stream: Function libraryDev() {return SRC (srcpath.library).pipe(dest(distpath.library)).pipe(reload({  stream: Function imagesDev() {return SRC (srcpath.images).pipe(dest(distpath.images)).pipe(reload({ stream: Function htmlDev() {return SRC (srcpath.html).pipe(include({})).pipe(dest(distpath.html)) .pipe(reload({stream: true}))} function cleanDir() {return SRC ('dist/*').pipe({read: Function browser() {browsersync.init ({server: {baseDir: './dist',}}) watchDev(); } function watchDev() {console.log(" start monitoring ") watch(srcpath.css, function(cb) {cssDev()}); watch(srcPath.less, function(cb) { lessDev() }); watch(srcPath.html, function(cb) { htmlDev() }); watch(srcPath.js, function(cb) { jsDev() }); watch(srcPath.library, function(cb) { libraryDev() }); watch(srcPath.images, function(cb) { imagesDev() }); } exports.dev = series(cleanDir, parallel(libraryDev, cssDev, lessDev, imagesDev, jsDev, htmlDev), browser)Copy the code

Type gulp dev on the console and the browser will start. The default port number is 3000. When the file is updated, it will listen and update.

The production environment

Production environment needs:

  1. Code compression
  2. Js and CSS generate hash names
  3. Adding prefixes to CSS
  4. Image compression
const gulp = require('gulp'); const { series, parallel, watch, src, dest } = require('gulp'); // const autoprefixer = require('gulp-autoprefixer'); const include = require('gulp-file-include'); const clean = require('gulp-clean'); // const less = require('gulp-less'); const babel = require('gulp-babel'); const css_base64 = require('gulp-css-base64'); // const minifyHtml = require('gulp-htmlmin'); const minifyImage = require('gulp-imagemin'); const minifyJs = require('gulp-uglify'); const minifyCss = require('gulp-clean-css'); // version control const rev = require('gulp-rev'); const revCollector = require('gulp-rev-collector'); const delOriginal = require('gulp-rev-delete-original'); // browser const browserSync = require('browser-sync').create(); const reload = browserSync.reload; / / source file path const srcPath = {root: 'SRC', HTML: [' SRC / / *. * * HTML ', '. The SRC/include / / *. * * HTML '], images: 'SRC/images / *, CSS: 'src/css/*.css', less: 'src/less/*.less', js: 'src/js/*.js', library: 'src/library/*.js' }; // Build build path const buildPath = {root: 'build', HTML: 'build', images: 'build/images', CSS: 'build/ CSS ', less: 'build/less', js: 'build/js', library: 'build/library', manifest: 'build/**/*.json', }; Function libraryBuild() {return SRC (srcpath.library).pipe(minifyJs()).pipe(dest(buildpath.library)); } function cssBuild() {return SRC ([buildpath.manifest, buildPath.css + '/*.css']) .pipe(revCollector()) .pipe(rev()) .pipe(delOriginal()) .pipe(dest(buildPath.css)) .pipe(rev.manifest()) .pipe(dest(buildPath.css)) } function cssCompile() { return src([srcPath.css]) .pipe(css_base64({ maxWeightResource: 8 * 1024, }).pipe(autoprefixer()).pipe(minifyCss()).pipe(dest(buildpath.css))} function lessBuild() {return src([buildPath.manifest, buildPath.less + '/*.css']) .pipe(revCollector()) .pipe(rev()) .pipe(delOriginal()) .pipe(dest(buildPath.less)) .pipe(rev.manifest()) .pipe(dest(buildPath.less)) } function lessCompile() { return src([srcPath.less]) .pipe(css_base64({ maxWeightResource: 8 * 1024, })).pipe(autoprefixer()).pipe(minifyCss()).pipe(dest(buildpath.less))} return src(srcPath.js) .pipe(babel({ presets: ['env'], })) .pipe(minifyJs()) .pipe(rev()) .pipe(dest(buildPath.js)) .pipe(rev.manifest()) .pipe(dest(buildPath.js)) } //image Function imagesBuild() {return SRC (srcpath.images).pipe(minifyImage()).pipe(rev()).pipe(dest(buildpath.images)) .pipe(rev.manifest()).pipe(dest(buildpath.images))} function htmlBuild() {return SRC ([buildpath.manifest, ...srcPath.html]) .pipe(include({})) .pipe(revCollector({ replaceReved: true, })) .pipe(minifyHtml({ collapseWhitespace: Function cleanBuild() {return SRC ('build/*').pipe({read: False}))} manifest function cleanManifest() {return SRC ('build/**/*.json').pipe(clean({read: false })) } exports.build = series(cleanBuild, imagesBuild, jsBuild, libraryBuild, lessCompile, lessBuild, cssCompile, cssBuild, htmlBuild, cleanManifest)Copy the code

The console type gulp build to generate the build directory and upload the generated directory to the server

[20:27:33] Using gulpfile F:\gulp-demo\gulpfile.js [20:27:33] Starting 'build'... [20:27:33] Starting 'cleanBuild'... [20:27:33] Finished 'cleanBuild' after 37 ms [20:27:33] Starting 'imagesBuild'... [20:27:45] gulp-imagemin: Minified 2 images (saved 174 kB - 21.5%) [20:27:45] Finished 'imagesBuild' after 12 s [20:27:45] Starting 'jsBuild'... [20:27:46] Finished 'jsBuild' after 832 ms [20:27:46] Starting 'libraryBuild'... [20:27:46] Finished 'libraryBuild' after 3.77ms [20:27:46] Starting 'lessCompile'... [20:27:46] Finished 'lessCompile' after 66 ms [20:27:46] Starting 'lessBuild'... [20:27:46] Finished 'lessBuild' after 18 ms [20:27:46] Starting 'cssCompile'... [20:27:46] Finished 'cssCompile' after 8.67ms [20:27:46] Starting 'cssBuild'... [20:27:46] Finished 'cssBuild' after 13 ms [20:27:46] Starting 'htmlBuild'... [20:27:46] Finished 'htmlBuild' after 23 ms [20:27:46] Finished 'build' after 13 sCopy the code
Github address is attached:Download the demo