UNPKG

landers.gulp-helper

Version:

landers.gulp-helper

426 lines (379 loc) 15.2 kB
'use strict'; let plugin = require('gulp-load-plugins')(); let fs = require('fs'); let gulpOrder =require("gulp-order"); require('landers.prototype'); function array_normalize(mixed) { if (!mixed) return []; var arr = !Array.isArray(mixed) ? [mixed] : mixed; return arr.flatten().filterFalse().unique(); } // var browserSync = require('browser-sync').create(); // var reload = browserSync.reload; let Helper = { gulp: null, plugin: plugin, runSequence: null, obfuscator: null, dependency: null, packagePath: null, pipe: null, log: null, task: null, // 常用路径 path: { root: '.', node_modules: './node_modules', bower_components: './bower_components', src: './src', dist: './dist', dev: './dev', asset: './assets', temp: './temp', html2js: './temp/html2js', lib: './lib', html: './html', static: './static', vendor: './vendor', modules: './modules', config: './config', supports: { self: './supports', partials: './supports/partials', classes: './supports/classes', services: './supports/services', styles: './supports/styles' }, components: './components', framework_root: './framework', public: '../../public', _build: function(path, prefix) { prefix = prefix || this.root; if (path) { if (path.indexOf('./') === 0) { path = path.substring(1); } if (path.indexOf('/') < 0) { path = '/' + path; } } return path ? prefix + path : prefix; }, buildFramework: function(path, prefix) { prefix = prefix || ''; return this._build(path, prefix + this.framework_root); }, buildApp: function(path, prefix) { var options = Helper.options; // 来自打包框架自身 if (this.root == this.framework_root) { return null; } prefix = prefix || ''; return this._build(path, prefix + this.root); } }, /** * options: {domainLimit:{list: [], handle: js_file}} */ use: function(options){ this.gulp = options.gulp || require('gulp'); this.options = Object.extend(this.options, options); this.log = require('./modules/log').use(this); this.runSequence = require('run-sequence').use(this.gulp); let through2 = require('through2'); this.pipe = require('./modules/pipe').use(this, through2); this.obfuscator = require('./modules/obfuscator'); this.dependency = require('./modules/dependency'); this.packagePath = require('./modules/package-path'); this.task = require('./modules/task').use(this); return this; }, // 处理options options: require('minimist')(process.argv.slice(2), { string: 'env', default: { env: 'local', watch: false, debug: false, connect: false, notify: false, is_for_crx: false, is_framework_self: false, is_mini_html: false, is_mini_css: false, is_uglify: false, is_obfuscate: false, public_sub_path: '' } }), // 注册监控任务 watchers: {}, addWatcher: function(task_name, files){ if (typeof task_name !== 'string') { throw 'task_name 参数错误'; } if ((!this.watchers[task_name]) && this.options.watch) { // this.log.success(`新增监控任务 - ${task_name} - ` + files.join('-')); this.gulp.watch(files, [task_name]); this.watchers[task_name] = true; } }, checkFiles: function(files, callback){ var _this = this; if (this.options.debug) { this.log.showList(files); // let lodash = require('./supports/lodash.min'); // var array1 = files.map(function(item){ // return item.replace(_this.path.node_modules, ''); // }); // var array2 = fs.readFileSync('/tmp/temp.' + array1[0].split('.').last() + '.log', 'utf-8').split("\n"); // this.log.showList(lodash.difference(array1, array2)); // console.log('----------------------------'); // this.log.showList(lodash.difference(array2, array1)); } files.map(function(file, index){ if ( file.indexOf('*') == -1 && file.indexOf('!(') == -1 && !fs.existsSync(file) ){ _this.log.error(file + ' 不存在'); } if (index == files.length) callback(); }); }, packCss: function(task_name, src_files, dist_file, options){ options = Object.extend(this.options, options || {}); src_files = array_normalize(src_files); this.checkFiles(src_files); this.addWatcher(task_name, src_files); var stream = this.gulp.src(src_files) .pipe(this.pipe.default()) .pipe(plugin.concat(dist_file)) .pipe(plugin.if(options.is_mini_css, plugin.minifyCss())) .pipe(this.gulp.dest(this.path.root + '/')) .on('end', () => {}); }, packJs: function(task_name, src_files, dist_file, options){ options = Object.extend(this.options, options || {}); src_files = array_normalize(src_files); this.checkFiles(src_files); this.addWatcher(task_name, src_files); var setting = this.obfuscator.setting(options.obfuscator_setting || {}); return this.gulp.src(src_files) .pipe(this.pipe.default()) .pipe(plugin.concat(dist_file)) .pipe(plugin.if(options.is_uglify, plugin.uglify())) .pipe(plugin.if(options.is_obfuscate, plugin.javascriptObfuscator(setting))) .pipe(this.gulp.dest(this.path.root)) .on('end', () => {}); }, // 复制fonts copyFonts: function(task_name, src_files, dist_path){ src_files = array_normalize(src_files); this.addWatcher(task_name, src_files); dist_path = dist_path || this.path.asset + '/fonts/'; return this.copy(src_files, dist_path, '字体'); }, packByDependency: function(task_name, suffix, dist_file, is_recursion, preppends, appends){ preppends = array_normalize(preppends); appends = array_normalize(appends); var _this = this; // function get_dependency_packages(is_recursion) { // return is_recursion ? // _this.dependency.getCurrentRecursionPackages() : // _this.dependency.getCurrentPackages(); // } function get_dependency_files(is_recursion, suffix) { var packages, dep_files; if (is_recursion) { packages = _this.dependency.getCurrentRecursionPackages().filterFalse(); dep_files = _this.packagePath.getSrcFiles(suffix, packages); } else { packages = _this.dependency.getCurrentPackages().filterFalse(); dep_files = _this.packagePath.getPaths(suffix, packages); } return dep_files; } function get_append_files(config) { if (config) { if (config.constructor == Array) { return config; } if (config.constructor == String) { return [config]; } } else { return []; } } // var packages = get_dependency_packages(is_recursion).filterFalse(), // lib_files = _this.packagePath.getPaths(suffix, packages), var lib_files = get_dependency_files(is_recursion, suffix), appends_files = get_append_files(appends), preppends_files = get_append_files(preppends), files = array_normalize(preppends_files.concat(lib_files, appends_files)), pack_method = { 'css': _this.packCss, 'js': _this.packJs, 'font': _this.copyFonts }[suffix]; return pack_method.call(_this, task_name, files, dist_file); }, packHtml: function(task_name, src_files, module_name, prefix_path, dir_temp, options) { options = Object.extend(this.options, options || {}); src_files = array_normalize(src_files); this.checkFiles(src_files); this.addWatcher(task_name, src_files); return this.gulp.src(src_files) .pipe( plugin.if( options.is_mini_html, plugin.htmlmin({ // https://www.cnblogs.com/river-lee/p/4253075.html removeComments:true, //删除注释,但是会保留script和style中的注释 collapseWhitespace: true, //删除空格,总是保留一个空格 }) ) ) .pipe(plugin.ngHtml2js({ moduleName: module_name, prefix: prefix_path + '/' })) .pipe(this.gulp.dest(dir_temp)); }, cleanPaths: function(paths){ if (typeof paths == 'string') { paths = [paths]; } this.gulp.src(paths) .pipe(plugin.clean({ force: true, read: false })); }, // 清空生产环境 // cleanProduction: function(){ // if ( this.options.env !== 'production') { // throw '非生产环境,无需清空'; // } // var paths = [ // this.path.asset + '/css/app.css', // this.path.asset + '/css/lib.css', // this.path.asset + '/js/app.js', // this.path.asset + '/js/base.js', // this.path.asset + '/js/lib.js', // this.path.asset + '/modules', // this.path.asset + '/vendor' // ]; // return this.gulp.src(paths) // .pipe(plugins.clean({ // force: true // })); // }, // 复制文件 copy: function(src_files, path){ this.checkFiles(src_files); return this.gulp.src(src_files) .pipe(this.gulp.dest(path)); }, // 执行外部命令 exec: function(cmds) { if (Array.isArray(cmds)) { cmds = cmds.join(' && '); } require('child_process').exec(cmds); }, // 设置生产环境目录权限 exeChmod: function(){ if (this.options.env !== 'production') { throw '非生产环境,运行此操作'; } this.exec('chmod -R +777 ' + this.path.dist); }, // 执行gz压缩 exeGz: function(task_name, src_file, dist_file){ dist_file = dist_file || `${src_file}.gz`; this.checkFiles([src_file]); this.addWatcher(task_name, [src_file]); this.exec(`gzip -f -c -9 ${src_file} > ${dist_file}`); }, getCurrentPackage:function(key){ var content = fs.readFileSync('./package.json'); var data = JSON.parse(content); if (!data) throw 'package.json 内容有误'; return key ? data[key] : data; }, startServer: function(dir){ var host = this.options.host || '127.0.0.1'; var port = this.options.port || '3333'; if (host && port) { /*设置服务器*/ plugin.connect.server({ root: dir || './', //要运行哪个目录 livereload: false, //是否热更新。 host: host, port:port //端口号 }); //通过浏览器把指定的地址 (http://localhost:9999)打开。 // plugin.open('http://' + host + ':' + port); } }, // 压缩html compressHtml: function(task_name, src_file, dist_file, options){ options = Object.extend({ removeComments: true,//清除HTML注释 collapseWhitespace: true,//压缩HTML collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input /> removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input /> removeScriptTypeAttributes: true,//删除<script>的type="text/javascript" removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css" minifyJS: true,//压缩页面JS minifyCSS: true//压缩页面CSS }, options); this.checkFiles([src_file]); this.addWatcher(task_name, [src_file]); return this.gulp.src(src_file) .pipe(plugin.replace('{{Math.random()}}', Math.random())) .pipe(plugin.htmlmin(options)) .pipe(plugin.concat(dist_file)) .pipe(this.gulp.dest(this.path.root)); }, // 编译html compileHtml: function(task_name, src_file, dist_file){ this.checkFiles([src_file]); this.addWatcher(task_name, [src_file]); return this.gulp.src(src_file) .pipe(plugin.useref()) .pipe(plugin.if('*.js', plugin.uglify())) .pipe(plugin.if('*.css', plugin.minifyCss())) .pipe(plugin.revReplace()) .pipe(this.gulp.dest(this.path.temp + '/')); } // taskBuildHtmlToTemp: function(file){ // return this.gulp.src(file) // .pipe(plugin.useref()) // .pipe(plugin.if('*.js', plugin.uglify())) // .pipe(plugin.if('*.css', plugin.minifyCss())) // .pipe(plugin.revReplace()) // // .pipe(plugin.append('')) // .pipe(this.gulp.dest(this.path.temp + '/')); // }, // 替换引用为代码 // taskReplaceRefWithCodeInTemp: function(source_html, dist_html){ // var js_path = 'asset/__pack.js'; // var css_path = 'asset/__pack.css'; // var that = this; // var js_code = fs.readFileSync(this.path.temp + '/' + js_path, 'utf-8'); // var css_code = fs.readFileSync(this.path.temp + '/' + css_path, 'utf-8'); // var html_code = fs.readFileSync(this.path.temp + '/' + source_html, 'utf-8') // .replace(/\n/g, ''); // var build_dist = function(html_code, css_code, js_code){ // html_code = html_code.replace('<script src="' + js_path + '"></script>', function(){ // return '<script>' + js_code + '</script>'; // }).replace('<link rel="stylesheet" href="' + css_path + '">', function(){ // return '<style>' + css_code + '</style>'; // }); // fs.writeFileSync(dist_html, html_code); // return that.taskClean(that.path.temp); // }; // if (this.options.env == 'production') { // js_code = that.obfuscator(js_code); // } // build_dist(html_code, css_code, js_code); // }, }; module.exports = Helper;