Gulp监听文件改动并压缩

package.json

{
  "name": "gulp-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "gulp dev --gulpfile ./gulpFile.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.6.4",
    "@babel/preset-env": "^7.6.3",
    "babel-core": "^6.26.3",
    "babel-preset-es2015": "^6.24.1",
    "del": "^5.1.0",
    "gulp": "^4.0.2",
    "gulp-babel": "^7.0.1",
    "gulp-less": "^4.0.1",
    "gulp-minify-css": "^1.2.4",
    "gulp-rename": "^1.4.0",
    "gulp-sass": "^4.0.2",
    "gulp-uglify": "^3.0.2",
    "gulp-watch": "^5.0.1"
  }
}

gulpFile.js

var gulp = require('gulp');
// 为了解决gulp的watch只监听一次的问题
var watch = require('gulp-watch');
var sass = require('gulp-sass');
var less = require('gulp-less');
var rename = require('gulp-rename');
var minifycss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
const babel = require('gulp-babel');
const del = require('del');

// 编译压缩scss
gulp.task('dev-css', () => {
  watch('./src/*.scss', () => {
    console.log('监听scss变动')
    // 清空打包完的css文件夹
    del('./dist/css/*');
    gulp.src('./src/*.scss')
        .pipe(sass())
        .pipe(rename({ suffix: '.min' }))
        .pipe(minifycss())
        .pipe(gulp.dest('./dist/css'))
  })
})

// 压缩js
gulp.task('dev-js', () => {
  watch('./src/*.js', () => {
    console.log('监听js变动')
    // 清空打包完的js文件夹
    del('./dist/js/*');
    gulp.src('./src/*.js')
        .pipe(rename({ suffix: '.min' }))
        .pipe(babel({
          presets: ['env']
        }))
        .pipe(uglify())
        .pipe(gulp.dest('./dist/js'))
  })
})

gulp.task('dev', gulp.parallel(['dev-css', 'dev-js']));

 

 

你可能感兴趣的:(前端工程化)