验证中...
私信发送成功
语言: JavaScript
分类: JavaScript 工具
最后更新于 2017-12-08 17:35
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('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, //省略布尔属性的值 <input checked="true"/> ==> <input checked />
removeEmptyAttributes: true, //删除所有空格作属性值 <input id="" /> ==> <input />
removeScriptTypeAttributes: false, //删除<script>的type="text/javascript"
removeStyleLinkTypeAttributes: false, //删除<style>和<link>的type="text/css"
minifyJS: true, //压缩页面JS
minifyCSS: true //压缩页面CSS
};
return gulpPipe(app.srcPath + '/**/*.{' + exts.html + '}')
// `changed` 任务需要提前知道目标目录位置
// 才能找出哪些文件是被修改过的
.pipe(changed(app.devPath))
// 只有被更改过的文件才会通过这里
.pipe(gulp.dest(app.devPath))
// .pipe(htmlmin(options))
// .pipe(gulp.dest(app.prdPath))
});
// 处理css
gulpTask('css', function(e) {
let autoprefixerOptions = {
browsers: ['last 4 versions'],
cascade: true, // 美化属性,默认true
add: true, // 是否添加前缀,默认true
remove: true, // 删除过时前缀,默认true
flexbox: true, // 为flexbox属性添加前缀,默认true
};
return gulpPipe(`${app.srcPath}/**/*.{${exts.css}}`)
// 添加css前缀
.pipe(changed(app.devPath))
.pipe(autoprefixer(autoprefixerOptions))
.pipe(gulp.dest(app.devPath))
// 压缩css
// .pipe(cleanCSS(cssminifyOptions))
// .pipe(gulp.dest(app.prdPath))
});
// 处理所有文件;
gulpTask('oct', function() {
return gulpPipe([app.srcPath + '/**/*.*'])
.pipe(changed(app.devPath))
.pipe(gulp.dest(app.devPath))
// .pipe(gulp.dest(app.prdPath))
});
// ++++++ task config ++++++
gulp.task('server', ['build','watcher'], function() {
connect.server(serverConfig);
}).on('end', function(params) {
});
// 打包项目
gulp.task('build', ['del', 'dev']);
gulp.task('dev', function(cb) {
return gulpSequence('oct', cb);
});
// 默认执行 server
gulp.task('default', ['server']);
// wactcher
gulp.task('watcher', function() {
// 监听文件的变化
let watcher = watch([app.srcPath + '/**/*.*'], {
events: ['add', 'change'],
read: false
}, function(e) {
// console.log(e)
gulp.start('dev');
});
// 监听删除文件
watcher.on('unlink', onUnlink);
// 捕获异常
watcher.on('error', onError);
});
/**
* 删除文件处理
*/
function onUnlink(filePath) {
// console.log(filePath)
let oldPath = filePath.replace(path.resolve(app.srcPath), '').split('\\').join('/');
let newPath = oldPath;
// 提示删除的文件
let tips = ['unlink ::', 'oldPath == ', app.srcPath + oldPath, ' || newPath == ', app.devPath + newPath].join('');
// 删除文件
del(app.devPath + newPath).then(function(e) {
console.log(' 删除成功 =:= ' + tips);
}).catch(function(e) {
console.log(' 删除失败 =:= ' + tips);
});
}
/**
* 异常处理
*/
function onError(e) {
console.log('=== err ===');
console.log(e);
}
// 捕获 js 异常
process.on('uncaughtException', function(err) {
console.log('=== err ===')
console.log(err)
});
module.exports = gulp;

评论列表( 0 )

你可以在登录后,对此项目发表评论

4_float_left_people 4_float_left_close