メインのコンテンツにスキップ

CLI の使用

terser [input files] [options]

Terser は、複数の入力ファイルを受け取ることができます。まず入力ファイルを指定し、次に入力オプションを指定することを推奨します。Terser は、入力ファイルを順番に解析し、圧縮オプションを適用します。ファイルは同じグローバルスコープで解析され、つまり、あるファイルから別のファイルで宣言された変数 / 関数への参照は適切に一致します。

オプションを取るコマンドライン引数 (たとえば、--parse、--compress、--mangle、および --format) は、デフォルトのオプションの上書きをコンマ区切りで取り込むことができます。たとえば

terser input.js --compress ecma=2015,computed_props=false

入力ファイルが指定されていない場合、Terser は STDIN から読み取ります。

入力ファイルの前にオプションを渡すには、入力ファイルをオプション引数として使用しないように、2 つのダッシュで 2 つを区別します。

terser --compress --mangle -- input.js

コマンドラインオプション

    -h, --help                  Print usage information.
`--help options` for details on available options.
-V, --version Print version number.
-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 and DOM
API props.
`debug` Add debug prefix and suffix.
`keep_quoted` Only mangle unquoted properties, quoted
properties are automatically reserved.
`strict` disables quoted properties
being automatically reserved.
`regex` Only mangle matched property names.
`only_annotated` Only mangle properties defined with /*@__MANGLE_PROP__*/.
`reserved` List of names that should not be mangled.
-f, --format [options] Specify format options.
`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.
`wrap_func_args` Wrap function arguments in parenthesis.
-o, --output <file> Output file path (default STDOUT). Specify `ast` or
`spidermonkey` to write Terser 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 e.g. "@license",
or start with "!". You can optionally pass one of the
following arguments to this flag:
- "all" to keep all comments
- `false` to omit comments in the output
- 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.
--ecma <version> Specify ECMAScript release: 5, 2015, 2016, etc.
-e, --enclose [arg[:value]] Embed output in a big function with configurable
arguments and values.
--ie8 Support non-standard Internet Explorer 8.
Equivalent to setting `ie8: true` in `minify()`
for `compress`, `mangle` and `format` options.
By default Terser will not try to be IE-proof.
--keep-classnames Do not mangle/drop class names.
--keep-fnames Do not mangle/drop function names. Useful for
code relying on Function.prototype.name.
--module Input is an ES6 module. If `compress` or `mangle` is
enabled then the `toplevel` option, as well as strict mode,
will be enabled.
--name-cache <file> File to hold mangled name mappings.
--safari10 Support non-standard Safari 10/11.
Equivalent to setting `safari10: true` in `minify()`
for `mangle` and `format` options.
By default `terser` will not work around
Safari 10/11 bugs.
--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` Name and/or location of the output source.
`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.
--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.

出力ファイルを宣言するには、--output (-o) を指定します。指定しない場合、出力は STDOUT に表示されます。

CLI ソースマップオプション

Terser は、圧縮された JavaScript のデバッグに非常に役立つソースマップファイルを生成できます。ソースマップを取得するには、--source-map --output output.js を渡します (ソースマップは output.js.map に書き込まれます)。

追加オプション

  • --source-map "filename='<NAME>'" ソースマップの名前を指定します。

  • --source-map "root='<URL>'" オリジナルファイルが見つかる URL を渡します。

  • --source-map "url='<URL>'" ソースマップの場所を指定する URL を指定します。指定しない場合、Terser は HTTP X-SourceMap が使用されていると想定し、//# sourceMappingURL= ディレクティブは省略されます。

たとえば

terser js/file1.js js/file2.js
-o foo.min.js -c -m
--source-map "root='http://foo.com/src',url='foo.min.

上記で、file1.jsfile2.jsを圧縮して改変し、出力をfoo.min.jsにドロップし、ソースマップをfoo.min.js.mapにドロップします。ソースマッピングではhttp://foo.com/src/js/file1.jshttp://foo.com/src/js/file2.jsが参照されます(実際には、http://foo.com/srcがソースマップのルートとして、元のファイルがjs/file1.jsjs/file2.jsとしてリストされます)。

構成ソースマップ

CoffeeScriptなどのコンパイラから出力されたJSコードを圧縮する場合、JSコードへのマッピングはあまり役に立ちません。代わりに、元のコード(つまり、CoffeeScript)にマップしたい 것입니다。Terserには、入力ソースマップを取り込むオプションがあります。CoffeeScript→コンパイルされたJSのマッピングがあると仮定すると、TerserはコンパイルされたJSの各トークンを元の場所にマッピングすることで、CoffeeScript→圧縮されたJSのマップを生成できます。

この機能を使用するには、--source-map "content='/path/to/input/source.map'"またはソースマップがソースにインラインで含まれている場合は--source-map "content=inline"を渡します。

CLI圧縮オプション

コンプレッサーを有効にするには--compress-c)を渡す必要があります。任意で、圧縮オプションのコンマ区切りのリストを渡すことができます。

オプションはfoo=barの形式で、または単にfooの形式です(後者は、trueに設定したいブール値オプションを意味します。実際には、foo=trueのショートカットです)。

terser file.js -c toplevel,sequences=false

CLIマングルオプション

難読化機能を有効にするには、--mangle-m)を渡す必要があります。次の(コンマ区切りの)オプションがサポートされます。

  • toplevel(デフォルトはfalse)--最上位スコープで宣言された名前を難読化します。

  • eval(デフォルトはfalse)--evalまたはwithが使用されているスコープで表示される名前を難読化します。

難読化が有効になっているが、特定の名前の難読化を防ぎたい場合は、--mangle reservedでそれらの名前を宣言できます--コンマ区切りの名前リストを渡します。たとえば

terser ... -m reserved=['$','require','exports']

requireexports、および$の名前が変更されないようにします。

CLIマングルプロパティ名(--mangle-props

注意:これは確実にコードが壊れます。良い経験則は、自分が何をやっているのか、これがどのように機能するのかを正確に理解し、このセクションの最後まで読まない限り、これを使用しないことです。

プロパティ名の難読化は、変数名の難読化とは異なる別のステップです。--mangle-propsを渡して有効にします。これを使用する最も危険性の少ない方法は、次のようにregexオプションを使用することです。

terser example.js -c -m --mangle-props regex=/_$/

これは、アンダースコアで終わるすべてのプロパティを難読化します。つまり、内部メソッドの難読化に使用できます。

デフォルトでは、組み込みのDOMプロパティとコアJavaScriptクラスのプロパティを除く、入力コード内のすべてのプロパティが難読化されます。そうしないとコードが壊れます。

  1. 難読化しているすべてのコードを制御する
  2. 通常、ファイルごとにTerserを呼び出すため、難読化されたオブジェクトをモジュール間で渡すことができなくなるため、モジュールバンドラーの使用は避けてください。
  3. definePropertyhasOwnPropertyなどの関数は、文字列を使用してオブジェクトプロパティを参照するため、何をやっているのかわからない場合は、コードが壊れますので、使用しないでください。

// example.js
var x = {
baz_: 0,
foo_: 1,
calc: function() {
return this.foo_ + this.baz_;
}
};
x.bar_ = 2;
x["baz_"] = 3;
console.log(x.calc());

すべてのプロパティを難読化する(JavaScriptの組み込みを除く)(非常に危険)

$ terser example.js -c passes=2 -m --mangle-props
var x={o:3,t:1,i:function(){return this.t+this.o},s:2};console.log(x.i());

reserved プロパティを除くすべてを難読化する(それでも非常に非安全)

$ terser example.js -c passes=2 -m --mangle-props reserved=[foo_,bar_]
var x={o:3,foo_:1,t:function(){return this.foo_+this.o},bar_:2};console.log(x.t());

regex に一致するすべてのプロパティを難読化する(非安全ではないが、それほど非安全でもない)

$ terser example.js -c passes=2 -m --mangle-props regex=/_$/
var x={o:3,t:1,calc:function(){return this.t+this.o},i:2};console.log(x.calc());

プロパティの難読化オプションを組み合わせる

$ terser example.js -c passes=2 -m --mangle-props regex=/_$/,reserved=[bar_]
var x={o:3,t:1,calc:function(){return this.t+this.o},bar_:2};console.log(x.calc());

これを役立てるには、デフォルトで標準の JS 名と DOM API プロパティの難読化を回避する(オーバーライドするには --mangle-props builtins を使用する)。

どのプロパティ名を難読化するのかを定義するために正規表現を使用できる。例えば、--mangle-props regex=/^_/ は、アンダースコアで始まるプロパティ名だけを難読化する。

このオプションを使用して複数のファイルを圧縮する場合、最終的に一緒に動作させるためには、すべてのファイルでプロパティが同じ名前に難読化されるように何らかの方法で確実に対応する必要がある。これには、--name-cache filename.json を渡し、Terser はこれらのマッピングをファイルに保持する。その後、このファイルを再利用できる。最初は空にしておく。例

$ rm -f /tmp/cache.json  # start fresh
$ terser file1.js file2.js --mangle-props --name-cache /tmp/cache.json -o part1.js
$ terser file3.js file4.js --mangle-props --name-cache /tmp/cache.json -o part2.js

これで、part1.jspart2.js は、難読化されたプロパティ名に関して互換性が出る。

単一の Terser 呼び出しですべてのファイルを圧縮する場合、名前キャッシュを使用する必要はない。

引用符のない名前の難読化 (--mangle-props keep_quoted)

引用符付きのプロパティ名を使用する (o["foo"]) と、そのプロパティ名 (foo) が予約されるため、スクリプト全体で引用符なしのスタイル (o.foo) で使用されても難読化されない。例

// stuff.js
var o = {
"foo": 1,
bar: 3
};
o.foo += o.bar;
console.log(o.foo);
$ terser stuff.js --mangle-props keep_quoted -c -m
var o={foo:1,o:3};o.foo+=o.o,console.log(o.foo);

プロパティ名の難読化のデバッグ

--mangle-props debug を渡すことで、プロパティ名を完全に隠蔽せずに難読化することもできる。例えば、このオプションを使用すると、プロパティ o.fooo._$foo$_ に難読化される。これにより、大規模なコードベースのプロパティを難読化しながら、コードをデバッグし、難読化がどこで問題を引き起こしているかを特定することができる。

$ terser stuff.js --mangle-props debug -c -m
var o={_$foo$_:1,_$bar$_:3};o._$foo$_+=o._$bar$_,console.log(o._$foo$_);

--mangle-props debug=XYZ を使用してカスタムサフィックスを渡すこともできる。これにより、o.fooo._$foo$XYZ_ に難読化される。これは、スクリプトをコンパイルするたびにこれを変更して、プロパティがどのように難読化されたかを特定できる。1 つの方法は、コンパイルごとに乱数を渡して、異なる入力(新しいプロパティで入力スクリプトを更新する場合など)によって難読化が変化することをシミュレートし、ストレージに難読化されたキーを書き込むような間違いを見つけるのに役立てることだ。