uglyJS 壓縮醜化介紹

uglyJS 功能:醜化 JS 文件,有效減小 js 文件大小;

基本使用

0、環境配置

如果有 es6 代碼,假設已經安裝了 babel 並可以成功將ES6轉換成ES5代碼。(項目沒有使用webpack進行打包)

1、安裝庫

npm install uglify-js --save-dev

2、修改配置

package.json 改成下面的配置

"scripts": {
  "clean": "rm -rf dist && mkdir dist && rm -rf lib && mkdir lib",
  "build": "./node_modules/.bin/babel src --out-dir dist",
  "ugly": "uglifyjs dist/**.js --output lib/leetcode.min.js --compress --mangle",
  "prepublish": "npm run clean && npm run build && npm run ugly"
},

常用配置說明

–output 輸出目錄(默認爲空,直接輸出到終端)

–compress 壓縮文件

–mangle 壓縮名稱

3、醜化

運行 npm run prepublish 即可編輯成ES5(dist)和醜化(lib)leetcode.min.js(詳細步驟如下)

3.1 刪除 dist lib 目錄,並新建文件夾;

3.2 使用 babel 編譯 src 下面的全部文件,並放在 dist 目錄下面

3.3 使用 uglyfyjs 將 dist 目錄下面的醜化成 lib/leetcode.min.js 文件

4、優缺點

適合場合:

輸出單一文件;壓縮醜化適應ES5(ES6首先使用babel編譯後才能使用)

不適應場合:

如果 src 下面有多個文件,那麼結果只會壓縮成一個文件(先後次序不確定);

所以這種方法不使用多模塊多出口壓縮(使用webpack處理多模塊壓縮)

下面是官網中詳細配置說明

    -p, --parse <options>       Specify parser options:
                                `acorn`  Use Acorn for parsing.
                                `bare_returns`  Allow return outside of functions.
                                                Useful when minifying CommonJS
                                                modules and Userscripts that may
                                                be anonymous function wrapped (IIFE)
                                                by the .user.js engine `caller`.
                                `expression`  Parse a single expression, rather than
                                              a program (for parsing JSON).
                                `spidermonkey`  Assume input files are SpiderMonkey
                                                AST format (as JSON).
    -c, --compress [options]    Enable compressor/specify compressor options:
                                `pure_funcs`  List of functions that can be safely
                                              removed when their return values are
                                              not used.
    -m, --mangle [options]      Mangle names/specify mangler options:
                                `reserved`  List of names that should not be mangled.
    --mangle-props [options]    Mangle properties/specify mangler options:
                                `builtins`  Mangle property names that overlaps
                                            with standard JavaScript globals.
                                `debug`  Add debug prefix and suffix.
                                `domprops`  Mangle property names that overlaps
                                            with DOM properties.
                                `keep_quoted`  Only mangle unquoted properties.
                                `regex`  Only mangle matched property names.
                                `reserved`  List of names that should not be mangled.
    -b, --beautify [options]    Beautify output/specify output options:
                                `beautify`  Enabled with `--beautify` by default.
                                `preamble`  Preamble to prepend to the output. You
                                            can use this to insert a comment, for
                                            example for licensing information.
                                            This will not be parsed, but the source
                                            map will adjust for its presence.
                                `quote_style`  Quote style:
                                               0 - auto
                                               1 - single
                                               2 - double
                                               3 - original
                                `wrap_iife`  Wrap IIFEs in parenthesis. Note: you may
                                             want to disable `negate_iife` under
                                             compressor options.
    -o, --output <file>         Output file path (default STDOUT). Specify `ast` or
                                `spidermonkey` to write UglifyJS or SpiderMonkey AST
                                as JSON to STDOUT respectively.
    --comments [filter]         Preserve copyright comments in the output. By
                                default this works like Google Closure, keeping
                                JSDoc-style comments that contain "@license" or
                                "@preserve". You can optionally pass one of the
                                following arguments to this flag:
                                - "all" to keep all comments
                                - a valid JS RegExp like `/foo/` or `/^!/` to
                                keep only matching comments.
                                Note that currently not *all* comments can be
                                kept when compression is on, because of dead
                                code removal or cascading statements into
                                sequences.
    --config-file <file>        Read `minify()` options from JSON file.
    -d, --define <expr>[=value] Global definitions.
    -e, --enclose [arg[:value]] Embed everything in a big function, with configurable
                                argument(s) & value(s).
    --keep-fnames               Do not mangle/drop function names.  Useful for
                                code relying on Function.prototype.name.
    --name-cache <file>         File to hold mangled name mappings.
    --self                      Build UglifyJS as a library (implies --wrap UglifyJS)
    --source-map [options]      Enable source map/specify source map options:
                                `base`  Path to compute relative paths from input files.
                                `content`  Input source map, useful if you're compressing
                                           JS that was generated from some other original
                                           code. Specify "inline" if the source map is
                                           included within the sources.
                                `filename`  Filename and/or location of the output source
                                            (sets `file` attribute in source map).
                                `includeSources`  Pass this flag if you want to include
                                                  the content of source files in the
                                                  source map as sourcesContent property.
                                `root`  Path to the original source to be included in
                                        the source map.
                                `url`  If specified, path to the source map to append in
                                       `//# sourceMappingURL`.
    --timings                   Display operations run time on STDERR.
    --toplevel                  Compress and/or mangle variables in top level scope.
    --verbose                   Print diagnostic messages.
    --warn                      Print warning messages.
    --wrap <name>               Embed everything in a big function, making the
                                “exports” and “global” variables available. You
                                need to pass an argument to this option to
                                specify the name that your module will take
                                when included in, say, a browser.

參考鏈接

官網

http://lisperator.net/uglifyjs/

https://github.com/mishoo/UglifyJS2

其他文檔

https://www.jianshu.com/p/dd847647b7e4

附錄

另一個壓縮工具 babel-plugin-uglify,babel 插件。使用人數不多(三年沒有更新),代碼簡單,可以參考。

UglifyJS integration for Babel.

It will allow you to integrate UglifyJS minifier into Babel pipeline without a need for generating code from Babel and parsing back into UglifyJS just to minify it and generate back again. You can find a bit more detailed article on this in my blog.

安裝

$ npm install babel-plugin-uglify --save-dev

使用

Note that plugin should be always runned after any ES6 transformers (use :after suffix as shown below), as UglifyJS doesn’t understand ES6 at all, and thus will just break if you have anything left untransformed.

Via .babelrc (推薦)

.babelrc

{
  "plugins": ["uglify:after"]
}

CLI

$ babel --plugins uglify:after script.js

Node API

require('babel').transform('code', {
  plugins: ['uglify:after']
});

核心代碼 Index.js

import { AST_Node, Compressor, TreeWalker } from 'uglify-js';

var compressor = Compressor();

class LocationFixer extends TreeWalker {
	constructor(path) {
		var filename = path.hub.file.opts.filenameRelative;
		super(node => {
			node.start.file = node.end.file = filename;
		});
	}
}

export default ({ types: t }) => ({
	visitor: {
		Program(ast) {
			// Convert to UglifyJS AST
			var uAST = AST_Node.from_mozilla_ast(ast);

			// Fix locations (Babel doesn't insert `loc.source` into nodes for some reason)
			uAST.walk(new LocationFixer(this));

			// Compress
			uAST.figure_out_scope();
			uAST = uAST.transform(compressor);

			// Mangle names
			uAST.figure_out_scope();
			uAST.compute_char_frequency();
			uAST.mangle_names();

			// Convert back to ESTree AST
			return uAST.to_mozilla_ast();
		}
	}
});

官網鏈接

https://github.com/rreverser/babel-plugin-uglify

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章