gulp notes (from development to release)

Foreword: gulp is relatively simple, take advantage of time to sort out a set of structures you like. When you want to make some simple small websites, you can reuse them. The code has been tested and can be used directly.

Main implementation functions: ES6 conversion, sass compilation, synthesizing sprite images, css automatic prefixing, compressing and merging compiled css, img image compression, js compression, implementing monitoring and refreshing the browser, and sftp plugin uploading code to the server (not verified). )

Development environment: node v8.9.4 gulp v3.9.1

Directory Structure:

 

Go to package.json first

{
  "name": "gulpOnly",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "browser-sync": "^2.23.7",
    "get-gulp-args": "0.0.1",
    "gulp": "^3.9.1",
    "gulp-autoprefixer": "^5.0.0",
    "gulp-babel": "^7.0.1",
    "gulp-clean": "^0.4.0",
    "gulp-concat": "^2.6.1",
    "gulp-css-img-sprite": "^1.0.2",
    "gulp-imagemin": "^4.1.0",
    "gulp-minify-css": "^1.2.4",
    "gulp-sass": "^4.0.1",
    "gulp-sftp": "^0.1.5",
    "run-sequence": "^2.2.1",
    "streamfilter": "^1.0.7"
  },
  "dependencies": {
    "gulp-load-plugins": "^1.5.0",
    "gulp-uglify": "^3.0.0"
  }
}

Below is the gulpfile

const gulp = require('gulp');
const gulpLoadPlugins = require('gulp-load-plugins');
const plugins = gulpLoadPlugins({lazy: true }); // Load plugins in package.json, limited to plugins at the beginning of 
gulp const streamfilter = require('streamfilter'); // Used to filter files 
const runSequence = require(' run-sequence'); // Used to implement gulp synchronous execution 
const browserSync = require('browser-sync').create(); // Used to start the service and automatically refresh 
const getargs = require('get-gulp- args'); // used to get command line parameters 
const dist = 'dist'; // release directory 
const src = 'src'; // source directory 

const args = getargs(); // get command line parameters

// Server configuration 
const servers = {
    dev : {
        host: 'xx.xx.xx.dev',
        user: 'username',
        pass: 'password',
        remotePath : '/'
    },
    test : {
        host: 'xx.xx.xx.test',
        user: 'username',
        pass: 'password',
        remotePath : '/'
    }
};

let watch = function(){
    gulp.watch(src + '/**/*.html' , ['copy.html']); 
    gulp.watch(src + '/**/*.js' , ['babel']);
    gulp.watch(src + '/**/*.scss' , ['sass']);
    gulp.watch(src + '/image/**', ['imgMin']);
    gulp.watch([src+'/**']).on('change',browserSync.reload); 
}

gulp.task('clean', ()=>{
    return gulp.src(dist)
               .pipe(plugins.clean())
})

gulp.task('clean.html',()=>{
    return gulp
        .src([dist + '/**/*.html'])
        .pipe(plugins.clean());
});

gulp.task('clean.css',()=>{
    return gulp
        .src([dist + '/**/*.css'])
        .pipe(plugins.clean());
});

gulp.task('clean.js',()=>{
    return gulp
        .src([dist + '/**/*.js'])
        .pipe(plugins.clean());
});

gulp.task('clean.img',()=>{
    return gulp
        .src([dist + '/image/**/*'])
        .pipe(plugins.clean());
});

gulp.task('clean.slice',()=>{
    return gulp
        .src([dist + '/slice/**/*'])
        .pipe(plugins.clean());
});

gulp.task('copy',['clean'], () => {
    return gulp
        .src([src + '/**/*','!'+src+'/**/*.js','!'+src+'/**/*.scss','!'+src+'/image/**/*'])
        .pipe (gulp.dest (dist));
});
// sass compile, synthesize sprite image, compress and merge the compiled css, automatically prefix 
gulp.task('sass',['clean.css','clean.slice'], () => {
     return gulp
        .src([src + '/**/*.scss']) 
        .pipe(plugins.sass({outputStyle: 'expanded'})//编译sass
        .on('error', plugins.sass.logError))
        .pipe(plugins.cssImgSprite({ // Synthesize sprite image 
            cssDesDir: dist,
            imgDesDir: dist + '/slice',
            hash: true
        }))
        .pipe(plugins.autoprefixer({ // Auto prefix 
            browsers: ['last 2 versions','Safari >0', 'Explorer >0', 'Edge >0', 'Opera >0', 'Firefox >= 20'], // last 2 versions- the latest two versions of mainstream browsers 
            cascade: false , // format beautification 
            remove: true  // whether to remove unnecessary prefixes Default: true 
        }))
        .pipe(plugins.concat('main.css'))
        .pipe(plugins.minifyCss()) //压缩
        .pipe(gulp.dest(dist+'/css/'))
});

// Image compression 
gulp.task('imgMin',['clean.img'], ()=> {
     return gulp
        .src([src + '/image/*.*'])
        .pipe(plugins.imagein(({
              optimizationLevel: 3, 
              progressive: true, 
              interlaced: true})
         ))
        .pipe(gulp.dest(dist+"/image"))
});

//ES6转换
gulp.task('babel',['clean.js'], () => {
    return gulp
        .src([src + '/**/*.js'])
        .pipe(plugins.babel({
            presets: ['env']
        }))
        .pipe(plugins.uglify())
        .pipe (gulp.dest (dist));
});

// Start the local service 
gulp.task('server', ()=> {
    browserSync.init({
        notify : false,
        port: 9000,   // Port number 
        server:{
            baseDir:[ 'dist'] // Service root directory 
        }
    });
});

// Upload the code to the server 
gulp.task('upload', ()=> {
    const globParams = {
        allowEmpty : false,
        base : dist
    };
    let stream = gulp.src([dist + '/**/*'], globParams);
    args.servers.split(',').forEach(serverName => {
        const server = servers[serverName];
        if(!server){
            console.warn( 'Could not find the server', serverName, ', only support dev and test' );
             return ;
        }

        stream = stream.pipe(plugins.sftp(server));
    });

    return stream;

});

//开发
gulp.task('dev', function(done) {
    runSequence(['copy','imgMin','sass','babel'],'server');
    watch();
});

// Release, divided into dev development environment, test test environment 
gulp.task('deploy', function (){
     if (! args.servers){
        console.log('Usage:\ngulp deploy --servers=dev,test');
        return ;
    }
    runSequence(['copy','imgMin','sass','babel'],'upload');
});

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325168325&siteId=291194637