gulpfile.js const path = require('path');let gulp = require('gulp');let watch = require('gulp-watch');let ProxyMiddleware = require('http-proxy-middleware');let del = require('del')let connect = require('gulp-connect')let changed = require(
const path = require('path'); let gulp = require('gulp'); let watch = require('gulp-watch'); let ProxyMiddleware = require('http-proxy-middleware'); let del = require('del') let connect = require('gulp-connect') let changed = require('gulp-changed'); let gulpSequence = require('gulp-sequence').use(gulp) // 文件处理 let autoprefixer = require('gulp-autoprefixer') let htmlmin = require('gulp-htmlmin') // 捕获异常 let plumber = require('gulp-plumber') function resolve(fpath) { return path.join(__dirname, fpath); } // 目录 let app = { srcPath: resolve('src'), distRoot: resolve('dist'), devPath: resolve('dist/dev'), prdPath: resolve('dist/dist') }; let exts = { html: 'html,htm', css: 'css', js: 'js', }; /** * 生成随机端口 */ function randomPort() { var port = parseInt(Math.random()*65535) if(port < 5000 || port === this.port) { port = randomPort.call(this); } return port; } let ProxyConf = { origin: ['/v1/**', '!/v1/**.*', '!/v1/'], target: 'https://xxx.xxx.com', host: 'http://localhost:8081' }; /** * 生成代理列表 * @param {*} ProxyConf cofnig */ function generationOps(ProxyConf) { let proxyTable = []; let ProxyOptions = { changeOrigin: true, logLevel: 'debug', ignorePath: true, router: function(req) { let origin = req.originalUrl; let target = ProxyConf.target + origin; return target; }, target: ProxyConf.host }; proxyTable.push( ProxyMiddleware(ProxyConf.origin, ProxyOptions)); return proxyTable; } let proxyTable = generationOps(ProxyConf); // server config let serverConfig = { root: app.devPath, port: 8081, livereload:{ port: randomPort.call(this) }, // proxy middleware: function(options,e) { return proxyTable; } } /** * 添加错误处理 * @param {*} src */ function gulpPipe(src) { let stream = gulp.src(src) .pipe(plumber()) return stream } /** * 流完成后reload */ function gulpTask() { let arg = [].splice.call(arguments, 0); if(typeof arg[arg.length -1] === 'function') { let cb = arg.pop(); arg.push(function() { let stream = cb.call(this); return stream.pipe(connect.reload()); }) }; return gulp.task.apply(gulp, arg); } // 清除文件 gulp.task('del', function() { // You can use multiple globbing patterns as you would with `gulp.src` try { return del.sync([app.distRoot]) } catch (e) { console.log('删除失败') return gulp } }); gulpTask('html', function() { let options = { removeComments: true, //清除HTML注释 collapseWhitespace: true, //压缩HTML collapseBooleanAttributes: false, //省略布尔属性的值 ==> removeEmptyAttributes: true, //删除所有空格作属性值 ==> removeScriptTypeAttributes: false, //删除