Browse Source

优化js&css打包策略

zxlie 7 years ago
parent
commit
43d950d889

+ 1 - 0
apps/background/index.js

@@ -675,6 +675,7 @@ var BgPageInstance = (function () {
     return {
         init: _init,
         runHelper: _runHelper,
+        notify: notifyText,
         showColorPicker: _showColorPicker,
         tellMeAjaxDbgSwitch: _tellDevToolsDbgSwitchOn
     };

+ 1 - 14
apps/code-beautify/beautify-css.js

@@ -239,18 +239,5 @@
         return sweetCode;
     }
 
-    if (typeof define === "function") {
-        // Add support for require.js
-        define(function(require, exports, module) {
-            exports.css_beautify = css_beautify;
-        });
-    } else if (typeof exports !== "undefined") {
-        // Add support for CommonJS. Just put this file somewhere on your require.paths
-        // and you will be able to `var html_beautify = require("beautify").html_beautify`.
-        exports.css_beautify = css_beautify;
-    } else if (typeof window !== "undefined") {
-        // If we're running a web page and don't have either of the above, add our one global
-        window.css_beautify = css_beautify;
-    }
-
+    module.exports.css_beautify = window.css_beautify = css_beautify;
 }());

+ 4 - 25
apps/code-beautify/beautify-html.js

@@ -609,29 +609,8 @@
       return multi_parser.output.join('');
     }
 
-    if (typeof define === "function") {
-        // Add support for require.js
-        define(function(require, exports, module) {
-            var js_beautify  = require('./beautify.js').js_beautify;
-            var css_beautify = require('./beautify-css.js').css_beautify;
-
-            exports.html_beautify = function(html_source, options) {
-                return style_html(html_source, options, js_beautify, css_beautify);
-            };
-        });
-    } else if (typeof exports !== "undefined") {
-        // Add support for CommonJS. Just put this file somewhere on your require.paths
-        // and you will be able to `var html_beautify = require("beautify").html_beautify`.
-        var js_beautify  = require('./beautify.js').js_beautify;
-        var css_beautify = require('./beautify-css.js').css_beautify;
-
-        exports.html_beautify = function(html_source, options) {
-            return style_html(html_source, options, js_beautify, css_beautify);
-        };
-    } else if (typeof window !== "undefined") {
-        // If we're running a web page and don't have either of the above, add our one global
-        window.html_beautify = function(html_source, options) {
-            return style_html(html_source, options, window.js_beautify, window.css_beautify);
-        };;
-    }
+    // If we're running a web page and don't have either of the above, add our one global
+    module.exports.html_beautify = window.html_beautify = function(html_source, options) {
+        return style_html(html_source, options, window.js_beautify, window.css_beautify);
+    };
 }());

+ 1 - 15
apps/code-beautify/beautify.js

@@ -1446,19 +1446,5 @@
         }
     }
 
-
-    if (typeof define === "function") {
-        // Add support for require.js
-        define(function(require, exports, module) {
-            exports.js_beautify = js_beautify;
-        });
-    } else if (typeof exports !== "undefined") {
-        // Add support for CommonJS. Just put this file somewhere on your require.paths
-        // and you will be able to `var js_beautify = require("beautify").js_beautify`.
-        exports.js_beautify = js_beautify;
-    } else if (typeof window !== "undefined") {
-        // If we're running a web page and don't have either of the above, add our one global
-        window.js_beautify = js_beautify;
-    }
-
+    module.exports.js_beautify = window.js_beautify = js_beautify;
 }());

+ 6 - 8
apps/code-beautify/index.js

@@ -29,8 +29,6 @@ new Vue({
     methods: {
         format: function () {
             let txtResult = '';
-            let beautifierFunc = () => {
-            };
 
             switch (this.selectedType) {
                 case 'Javascript':
@@ -47,16 +45,16 @@ new Vue({
                         unescape_strings: false,
                         wrap_line_length: "120"
                     };
-                    beautifierFunc = Tarp.require('./beautify.js').js_beautify;
-                    txtResult = beautifierFunc(this.sourceContent, opts);
+                    Tarp.require('./beautify.js');
+                    txtResult = js_beautify(this.sourceContent, opts);
                     break;
                 case 'CSS':
-                    beautifierFunc = Tarp.require('./beautify-css.js').css_beautify;
-                    txtResult = beautifierFunc(this.sourceContent);
+                    Tarp.require('./beautify-css.js');
+                    txtResult = css_beautify(this.sourceContent);
                     break;
                 case 'HTML':
-                    beautifierFunc = Tarp.require('./beautify-html.js').html_beautify;
-                    txtResult = beautifierFunc(this.sourceContent);
+                    Tarp.require('./beautify-html.js');
+                    txtResult = html_beautify(this.sourceContent);
                     break;
                 case 'SQL':
                     Tarp.require('./vkbeautify.js');

File diff suppressed because it is too large
+ 0 - 0
apps/en-decode/index.html


+ 55 - 22
apps/image-base64/index.js

@@ -17,33 +17,20 @@ new Vue({
         chrome.runtime.onMessage.addListener((request, sender, callback) => {
             if (request.type === MSG_TYPE.TAB_CREATED_OR_UPDATED && request.event === MSG_TYPE.IMAGE_BASE64) {
                 if (request.content) {
-                    this.convertOnline(request.content);
+                    this.convertOnline(request.content, flag => {
+                        if (!flag) {
+                            chrome.extension.getBackgroundPage().BgPageInstance.notify({
+                                message: '抱歉,' + request.content + ' 对应的图片未转码成功!'
+                            });
+                        }
+                    });
                 }
             }
         });
 
         //监听paste事件
         document.addEventListener('paste', (event) => {
-            let items = event.clipboardData.items || {};
-
-            // 优先处理图片
-            for (let index in items) {
-                let item = items[index];
-                if (/image\//.test(item.type)) {
-                    let file = item.getAsFile();
-                    return this._getDataUri(file);
-                }
-            }
-
-            // 然后处理url
-            for (let index in items) {
-                let item = items[index];
-                if (/text\/plain/.test(item.type)) {
-                    return item.getAsString(url => {
-                        this.convertOnline(url);
-                    });
-                }
-            }
+            this.paste(event);
         }, false);
 
         // 监听拖拽
@@ -93,7 +80,7 @@ new Vue({
             reader.readAsDataURL(file);
         },
 
-        convertOnline: function (onlineSrc) {
+        convertOnline: function (onlineSrc, callback) {
             let that = this;
             that.previewSrc = onlineSrc;
             let image = new Image();
@@ -118,8 +105,12 @@ new Vue({
                     that.sizeOri = width + 'x' + height;
                     that.sizeBase = that._sizeFormat(that.resultContent.length);
 
+                    callback && callback(true);
                 })(image, 0, 0, width, height);
             };
+            image.onerror = function () {
+                callback && callback(false);
+            };
         },
 
         convert: function () {
@@ -136,6 +127,48 @@ new Vue({
         upload: function (evt) {
             evt.preventDefault();
             this.$refs.fileBox.click();
+        },
+
+        paste: function (event) {
+            let items = event.clipboardData.items || {};
+
+            // 优先处理图片
+            for (let index in items) {
+                let item = items[index];
+                if (/image\//.test(item.type)) {
+                    let file = item.getAsFile();
+                    return this._getDataUri(file);
+                }
+            }
+
+            // 然后处理url
+            try {
+                // 逐个遍历
+                (async () => {
+                    for (let index in items) {
+                        let item = items[index];
+                        if (/text\/plain/.test(item.type)) {
+                            let url = await new Promise(resolve => {
+                                item.getAsString(url => resolve(url))
+                            });
+                            let flag = await new Promise(resolve => {
+                                this.convertOnline(url, flag => resolve(flag));
+                            });
+                            if (flag) break;
+                        }
+                    }
+                })();
+            } catch (ex) {
+                // 只能处理一个了
+                for (let index in items) {
+                    let item = items[index];
+                    if (/text\/plain/.test(item.type)) {
+                        return item.getAsString(url => {
+                            this.convertOnline(url);
+                        });
+                    }
+                }
+            }
         }
     }
 });

+ 12 - 14
apps/json-format/automatic.js

@@ -173,21 +173,19 @@ module.exports = (() => {
             $('body').html(_htmlFragment);
             _loadCss();
 
-            // 异步加载模式
-            Tarp.require('../json-format/format-lib', true).then(Json => {
-                Json.format(newSource);
-
-                // 如果是JSONP格式的,需要把方法名也显示出来
-                if (funcName != null) {
-                    if (fnTry && fnCatch) {
-                        $('#jfCallbackName_start').html('<pre style="padding:0">' + fnTry + '</pre>' + funcName + '(');
-                        $('#jfCallbackName_end').html(')<br><pre style="padding:0">' + fnCatch + '</pre>');
-                    } else {
-                        $('#jfCallbackName_start').html(funcName + '(');
-                        $('#jfCallbackName_end').html(')');
-                    }
+            // 格式化
+            Tarp.require('../json-format/format-lib').format(newSource);
+
+            // 如果是JSONP格式的,需要把方法名也显示出来
+            if (funcName != null) {
+                if (fnTry && fnCatch) {
+                    $('#jfCallbackName_start').html('<pre style="padding:0">' + fnTry + '</pre>' + funcName + '(');
+                    $('#jfCallbackName_end').html(')<br><pre style="padding:0">' + fnCatch + '</pre>');
+                } else {
+                    $('#jfCallbackName_start').html(funcName + '(');
+                    $('#jfCallbackName_end').html(')');
                 }
-            });
+            }
         }
     };
 

+ 5 - 1
apps/manifest.json

@@ -1,6 +1,6 @@
 {
   "name": "WEB前端助手(FeHelper)",
-  "version": "2018.04.2014",
+  "version": "2018.04.2318",
   "manifest_version": 2,
   "default_locale": "zh_CN",
   "description": "FE助手:包括JSON格式化、二维码生成与解码、信息编解码、代码压缩、美化、页面取色、正则表达式、时间转换工具、编码规范检测、页面性能检测、Ajax接口调试",
@@ -23,6 +23,10 @@
     ]
   },
   "options_page": "options/index.html",
+  "options_ui": {
+    "chrome_style": true,
+    "page": "options/index.html"
+  },
   "devtools_page": "ajax-debugger/index.html",
   "permissions": [
     "tabs",

+ 10 - 6
apps/static/js/utils.js

@@ -118,17 +118,21 @@ Date.prototype.format = function (pattern) {
  */
 window.alert = function (content) {
     window.clearTimeout(window.feHelperAlertMsgTid);
-    let elAlertMsg = $("#fehelper_alertmsg").hide();
-    if (!elAlertMsg.get(0)) {
-        elAlertMsg = $('<div id="fehelper_alertmsg" style="position:fixed;top:5px;right:5px;z-index:1000000">' +
+    let elAlertMsg = document.querySelector("#fehelper_alertmsg");
+    if (!elAlertMsg) {
+        let elWrapper = document.createElement('div');
+        elWrapper.innerHTML = '<div id="fehelper_alertmsg" style="position:fixed;top:5px;right:5px;z-index:1000000">' +
             '<p style="background:#000;display:inline-block;color:#fff;text-align:center;' +
-            'padding:10px 10px;margin:0 auto;font-size:14px;border-radius:4px;">' + content + '</p></div>').appendTo('body');
+            'padding:10px 10px;margin:0 auto;font-size:14px;border-radius:4px;">' + content + '</p></div>';
+        elAlertMsg = elWrapper.childNodes[0];
+        document.body.appendChild(elAlertMsg);
     } else {
-        elAlertMsg.find('p').text(content).end().show();
+        elAlertMsg.querySelector('p').innerHTML = content;
+        elAlertMsg.style.display = 'block';
     }
 
     window.feHelperAlertMsgTid = window.setTimeout(function () {
-        elAlertMsg.hide(100);
+        elAlertMsg.style.display = 'none';
     }, 3000);
 };
 

+ 1 - 1
apps/timestamp/index.js

@@ -34,6 +34,7 @@ new Vue({
             }
         },
         stampToLocale: function () {
+            Tarp.require('../static/js/utils');
             if (this.txtSrcStamp.length === 0) {
                 alert('请先填写你需要转换的Unix时间戳');
                 return;
@@ -42,7 +43,6 @@ new Vue({
                 alert('请输入合法的Unix时间戳');
                 return;
             }
-            Tarp.require('../static/js/utils');
             this.txtDesDate = (new Date(parseInt(this.txtSrcStamp, 10) * 1000)).format('yyyy-MM-dd HH:mm:ss');
         },
         localeToStamp: function () {

+ 94 - 10
gulpfile.js

@@ -13,6 +13,8 @@ let uglifycss = require('gulp-uglifycss');
 let htmlmin = require('gulp-htmlmin');
 let jsonmin = require('gulp-jsonminify');
 let fs = require('fs');
+let through = require('through2');
+let path = require('path');
 let pretty = require('pretty-bytes');
 let shell = require('shelljs');
 let runSequence = require('run-sequence');
@@ -24,33 +26,115 @@ gulp.task('clean', () => {
 });
 
 gulp.task('copy', () => {
-    return gulp.src(['apps/**/*.{gif,png,jpg,jpeg,cur}','!apps/static/screenshot/**/*']).pipe(copy('output'));
+    return gulp.src(['apps/**/*.{gif,png,jpg,jpeg,cur}', '!apps/static/screenshot/**/*']).pipe(copy('output'));
 });
 
 gulp.task('json', () => {
     return gulp.src('apps/**/*.json').pipe(jsonmin()).pipe(gulp.dest('output/apps'));
 });
 
-gulp.task('css', () => {
-    return gulp.src('apps/**/*.css').pipe(uglifycss()).pipe(gulp.dest('output/apps'));
-});
-
 gulp.task('html', () => {
     return gulp.src('apps/**/*.html').pipe(htmlmin({collapseWhitespace: true})).pipe(gulp.dest('output/apps'));
 });
 
+// 合并 & 压缩 js
 gulp.task('js', () => {
-    return gulp.src('apps/**/*.js').pipe(uglifyjs()).pipe(gulp.dest('output/apps'));
+    let jsMerge = () => {
+        return through.obj(function (file, enc, cb) {
+            let contents = file.contents.toString('utf-8');
+
+            let tpl = 'let #VARNAME# = (function(module){ #CODES# ; return module.exports; })({exports:{}});\r\n';
+
+            let merge = (fp, fc) => {
+                let js = {};
+
+                let rfc = fc.replace(/Tarp\.require\(\s*(['"])(.*)\1\s*\)/gm, function (frag, $1, mod, $2, code) {
+                    let mp = path.resolve(fp, '../' + mod + (/\.js$/.test(mod) ? '' : '.js'));
+                    let mc = fs.readFileSync(mp).toString('utf-8');
+
+                    frag = frag.replace(/[^\w]/g, '').replace('Tarprequire', 'TR');
+                    js[frag] = merge(mp, mc);
+                    return frag;
+                });
+
+                return Object.keys(js).map(k => {
+                    return tpl.replace('#VARNAME#', k).replace('#CODES#', () => js[k]);
+                }).join('; ') + rfc;
+            };
+
+            contents = merge(file.path, contents);
+            file.contents = new Buffer(contents);
+            this.push(file);
+            return cb();
+        })
+    };
+
+    return gulp.src('apps/**/*.js').pipe(jsMerge()).pipe(uglifyjs()).pipe(gulp.dest('output/apps'));
 });
 
+// 合并 & 压缩 css
+gulp.task('css', () => {
+
+    let cssMerge = () => {
+        return through.obj(function (file, enc, cb) {
+            let contents = file.contents.toString('utf-8');
+
+            let merge = (fp, fc) => {
+                return fc.replace(/\@import\s+(url\()?\s*(['"])(.*)\2\s*(\))?\s*;?/gm, function (frag, $1, $2, mod) {
+                    let mp = path.resolve(fp, '../' + mod + (/\.css$/.test(mod) ? '' : '.css'));
+                    let mc = fs.readFileSync(mp).toString('utf-8');
+                    return merge(mp, mc);
+                });
+            };
+
+            contents = merge(file.path, contents);
+            file.contents = new Buffer(contents);
+            this.push(file);
+            return cb();
+        })
+    };
+
+    return gulp.src('apps/**/*.css').pipe(cssMerge()).pipe(uglifycss()).pipe(gulp.dest('output/apps'));
+});
+
+// 清理冗余文件,并且打包成zip,发布到chrome webstore
 gulp.task('zip', () => {
-    // 压缩打包
-    shell.exec('cd output/ && zip -r fehelper.zip apps/ > /dev/null && cd ../');
+
+    // 读取manifest文件
+    let pathOfMF = './output/apps/manifest.json';
+    let manifest = require(pathOfMF);
+
+    // background、content-script中的文件,可以作为例外
+    let excludes = manifest.background.scripts.concat(manifest.content_scripts.map(cs => {
+        return cs.js.join(',');
+    }).join(',').split(','));
+
+    // ============冗余文件清理================================================
+    shell.cd('output/apps');
+    let fileList = shell.find('.').filter(file => {
+        let included = 'yes';
+        if (file.match(/\.css$/) && !/index\.css$/.test(file)) {
+            included = shell.grep('-l', file, './**/*.{css,html,js}').stdout;
+        } else if (file.match(/\.js$/) && !/index\.js$/.test(file)) {
+            included = shell.grep('-l', file.replace(/\.js$/, ''), './**/*.{html,js}').stdout;
+        }
+        return !included.trim().length;
+    });
+    fileList = fileList.filter(f => excludes.indexOf(f) === -1);
+    fileList.forEach(f => shell.rm('-rf', f));
+    shell.cd('../../');
+
+    // web_accessible_resources 中也不需要加载这些冗余的文件了
+    manifest.web_accessible_resources = manifest.web_accessible_resources.filter(f => fileList.indexOf(f) === -1);
+    fs.writeFileSync(pathOfMF, JSON.stringify(manifest));
+
+    // ============压缩打包================================================
+    shell.exec('cd output/ && rm -rf fehelper.zip && zip -r fehelper.zip apps/ > /dev/null && cd ../');
     let size = fs.statSync('output/fehelper.zip').size;
     size = pretty(size);
 
     console.log('\n\n================================================================================');
-    console.log('    当前版本:', require('./output/apps/manifest.json').version, '\t文件大小:', size);
+    console.log('    当前版本:', manifest.version, '\t文件大小:', size);
     console.log('    去Chrome商店发布吧:https://chrome.google.com/webstore/devconsole');
     console.log('================================================================================\n\n');
 });
@@ -65,7 +149,7 @@ gulp.task('watch', () => {
     gulp.watch('apps/**/*.*', (event) => {
         let wp = watchPath(event, './', './output');
         gulp.src(wp.srcPath).pipe(copy('output')).pipe(gcallback(() => {
-            console.log('> 文件发生变化,已编译:', wp.srcPath);
+            console.log(new Date().toLocaleString(), '> 文件发生变化,已编译:', wp.srcPath);
         }));
     });
 });

Some files were not shown because too many files changed in this diff