UNPKG

tpack-uglify-js

Version:

TPack 插件:使用 UglifyJS 压缩或格式化 JS。

104 lines (93 loc) 3.52 kB
/* * Copyright (C) 2016 xuld<xuld@vip.qq.com> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: *  * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ var UglifyJS = require("uglify-js"); /** * 压缩或格式化 JS。 * @param {BuildFile} file 要生成的文件。 * @param {Object} options 相关的选项。 * @see https://github.com/mishoo/UglifyJS */ module.exports = function uglifyJS(file, options) { // 设置默认值。 options = Object.assign({ inSourceMap: file.sourceMapData, outSourceMap: !!file.sourceMap }, options); if (options.parse !== false) { options.parse = Object.assign({ filename: file.srcPath }, options.parse); } if (options.compress !== false) { options.compress = Object.assign({ drop_console: true, dead_code: true, drop_debugger: true, global_defs: { DEBUG: false, RELEASE: true } }, options.compress); } if (options.output !== false) { options.output = Object.assign({ comments: /^!|@preserve|@license|@cc_on/ }, options.output); } options.fromString = true; // 设置警告函数。 var oldWarnFunction; if (options.warnings || options.compress.warnings) { oldWarnFunction = UglifyJS.AST_Node.warn_function; UglifyJS.AST_Node.warn_function = function (text) { var pos = /\s*\[\d+:(\d+),(\d+)\]$/.exec(text); if (pos) { file.warning("UglifyJsWarning", null, text.substr(0, pos.index), null, +pos[1], +pos[2]); } else { file.warning("UglifyJsWarning", null, text); } }; } // 生成。 var result; try { result = UglifyJS.minify(file.content, options); } catch (e) { // 可用的字段:e.message, e.stack, e.line, e.col, e.pos e.name = e.constructor.name === "JS_Parse_Error" ? "UglifyJsSyntaxError" : e.name || "UglifyJsError"; file.error(e); return; } finally { if (oldWarnFunction) { UglifyJS.AST_Node.warn_function = oldWarnFunction; } } // 保存。 file.content = result.code; if (result.map) { var map = JSON.parse(result.map); map.sources[0] = file.srcPath; file.sourceMap = map; } };