このプラグインは、JavaScriptを縮小/最小化するためにterserを使用します。
Webpack v5には、最新のterser-webpack-plugin
がすぐに使用できます。Webpack v5以降を使用していて、オプションをカスタマイズしたい場合は、それでもterser-webpack-plugin
をインストールする必要があります。Webpack v4を使用する場合は、terser-webpack-plugin
v4をインストールする必要があります。
始めるには、terser-webpack-plugin
をインストールする必要があります。
npm install terser-webpack-plugin --save-dev
または
yarn add -D terser-webpack-plugin
または
pnpm add -D terser-webpack-plugin
次に、プラグインをwebpack
設定に追加します。例:
webpack.config.js
const TerserPlugin = require("terser-webpack-plugin");
module.exports = {
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
},
};
お好みの方法でwebpack
を実行してください。
devtool
オプションにsource-map
、inline-source-map
、hidden-source-map
、nosources-source-map
の値のみ対応しています。
なぜ?
eval
はモジュールをeval("string")
でラップし、ミニファイアは文字列を処理しません。cheap
には列情報がなく、ミニファイアは1行しか生成しないため、マッピングは1つだけになります。サポートされているdevtool
値を使用すると、ソースマップの生成が可能になります。
test
型
type test = string | RegExp | Array<string | RegExp>;
デフォルト: /\.m?js(\?.*)?$/i
ファイルに一致させるためのテスト。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
test: /\.js(\?.*)?$/i,
}),
],
},
};
include
型
type include = string | RegExp | Array<string | RegExp>;
デフォルト: undefined
含めるファイル。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
include: /\/includes/,
}),
],
},
};
exclude
型
type exclude = string | RegExp | Array<string | RegExp>;
デフォルト: undefined
除外するファイル。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
exclude: /\/excludes/,
}),
],
},
};
parallel
型
type parallel = boolean | number;
デフォルト: true
マルチプロセス並列実行を使用してビルド速度を向上させます。デフォルトの同時実行数はos.cpus().length - 1
です。
注意
並列化によりビルド速度が大幅に向上するため、**強く推奨**します。
警告
Circle CIまたはCPUの実数の利用可能な数を提供しないその他の環境を使用している場合、
Error: Call retries were exceeded
を回避するために、CPUの数を明示的に設定する必要があります(#143、#202を参照)。
boolean
マルチプロセス並列実行を有効/無効にします。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
parallel: true,
}),
],
},
};
number
マルチプロセス並列実行を有効にし、同時実行数を設定します。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
parallel: 4,
}),
],
},
};
minify
型
type minify = (
input: {
[file: string]: string;
},
sourceMap: import("@jridgewell/trace-mapping").SourceMapInput | undefined,
minifyOptions: {
module?: boolean | undefined;
ecma?: import("terser").ECMA | undefined;
},
extractComments:
| boolean
| "all"
| "some"
| RegExp
| ((
astNode: any,
comment: {
value: string;
type: "comment1" | "comment2" | "comment3" | "comment4";
pos: number;
line: number;
col: number;
}
) => boolean)
| {
condition?:
| boolean
| "all"
| "some"
| RegExp
| ((
astNode: any,
comment: {
value: string;
type: "comment1" | "comment2" | "comment3" | "comment4";
pos: number;
line: number;
col: number;
}
) => boolean)
| undefined;
filename?: string | ((fileData: any) => string) | undefined;
banner?:
| string
| boolean
| ((commentsFile: string) => string)
| undefined;
}
| undefined
) => Promise<{
code: string;
map?: import("@jridgewell/trace-mapping").SourceMapInput | undefined;
errors?: (string | Error)[] | undefined;
warnings?: (string | Error)[] | undefined;
extractedComments?: string[] | undefined;
}>;
デフォルト: TerserPlugin.terserMinify
デフォルトのminify関数をオーバーライドできます。デフォルトでは、プラグインはterserパッケージを使用します。公開されていないバージョンまたはフォークを使用およびテストする場合に役立ちます。
警告
parallel
オプションが有効になっている場合、minify
関数内では常にrequire
を使用してください。.
webpack.config.js
// Can be async
const minify = (input, sourceMap, minimizerOptions, extractsComments) => {
// The `minimizerOptions` option contains option from the `terserOptions` option
// You can use `minimizerOptions.myCustomOption`
// Custom logic for extract comments
const { map, code } = require("uglify-module") // Or require('./path/to/uglify-module')
.minify(input, {
/* Your options for minification */
});
return { map, code, warnings: [], errors: [], extractedComments: [] };
};
// Used to regenerate `fullhash`/`chunkhash` between different implementation
// Example: you fix a bug in custom minimizer/custom function, but unfortunately webpack doesn't know about it, so you will get the same fullhash/chunkhash
// to avoid this you can provide version of your custom minimizer
// You don't need if you use only `contenthash`
minify.getMinimizerVersion = () => {
let packageJson;
try {
// eslint-disable-next-line global-require, import/no-extraneous-dependencies
packageJson = require("uglify-module/package.json");
} catch (error) {
// Ignore
}
return packageJson && packageJson.version;
};
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
myCustomOption: true,
},
minify,
}),
],
},
};
terserOptions
型
type terserOptions = {
compress?: boolean | CompressOptions;
ecma?: ECMA;
enclose?: boolean | string;
ie8?: boolean;
keep_classnames?: boolean | RegExp;
keep_fnames?: boolean | RegExp;
mangle?: boolean | MangleOptions;
module?: boolean;
nameCache?: object;
format?: FormatOptions;
/** @deprecated */
output?: FormatOptions;
parse?: ParseOptions;
safari10?: boolean;
sourceMap?: boolean | SourceMapOptions;
toplevel?: boolean;
};
デフォルト: デフォルト
Terser オプション。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
ecma: undefined,
parse: {},
compress: {},
mangle: true, // Note `mangle.properties` is `false` by default.
module: false,
// Deprecated
output: null,
format: null,
toplevel: false,
nameCache: null,
ie8: false,
keep_classnames: undefined,
keep_fnames: false,
safari10: false,
},
}),
],
},
};
extractComments
型
type extractComments =
| boolean
| string
| RegExp
| ((
astNode: any,
comment: {
value: string;
type: "comment1" | "comment2" | "comment3" | "comment4";
pos: number;
line: number;
col: number;
}
) => boolean)
| {
condition?:
| boolean
| "all"
| "some"
| RegExp
| ((
astNode: any,
comment: {
value: string;
type: "comment1" | "comment2" | "comment3" | "comment4";
pos: number;
line: number;
col: number;
}
) => boolean)
| undefined;
filename?: string | ((fileData: any) => string) | undefined;
banner?:
| string
| boolean
| ((commentsFile: string) => string)
| undefined;
};
デフォルト: true
コメントを別のファイルに抽出するかどうか(詳細を参照)。デフォルトでは、/^\**!|@preserve|@license|@cc_on/i
正規表現条件を使用してコメントのみを抽出し、残りのコメントを削除します。元のファイル名がfoo.js
の場合、コメントはfoo.js.LICENSE.txt
に保存されます。terserOptions.format.comments
オプションは、コメントを保持するかどうかを指定します。つまり、一部のコメント(注釈など)を保持しながら他のコメントを抽出したり、抽出されたコメントを保持することも可能です。
boolean
コメントの抽出を有効/無効にします。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
extractComments: true,
}),
],
},
};
string
all
またはsome
(/^\**!|@preserve|@license|@cc_on/i
正規表現を使用)のコメントを抽出します。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
extractComments: "all",
}),
],
},
};
RegExp
指定された式に一致するすべてのコメントが、別のファイルに抽出されます。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
extractComments: /@extract/i,
}),
],
},
};
function
指定された式に一致するすべてのコメントが、別のファイルに抽出されます。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
extractComments: (astNode, comment) => {
if (/@extract/i.test(comment.value)) {
return true;
}
return false;
},
}),
],
},
};
object
コメントの抽出条件、抽出ファイル名、バナーをカスタマイズできます。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
extractComments: {
condition: /^\**!|@preserve|@license|@cc_on/i,
filename: (fileData) => {
// The "fileData" argument contains object with "filename", "basename", "query" and "hash"
return `${fileData.filename}.LICENSE.txt${fileData.query}`;
},
banner: (licenseFile) => {
return `License information can be found in ${licenseFile}`;
},
},
}),
],
},
};
condition
型
type condition =
| boolean
| "all"
| "some"
| RegExp
| ((
astNode: any,
comment: {
value: string;
type: "comment1" | "comment2" | "comment3" | "comment4";
pos: number;
line: number;
col: number;
}
) => boolean)
| undefined;
抽出するコメントの条件。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
extractComments: {
condition: "some",
filename: (fileData) => {
// The "fileData" argument contains object with "filename", "basename", "query" and "hash"
return `${fileData.filename}.LICENSE.txt${fileData.query}`;
},
banner: (licenseFile) => {
return `License information can be found in ${licenseFile}`;
},
},
}),
],
},
};
filename
型
type filename = string | ((fileData: any) => string) | undefined;
デフォルト: [file].LICENSE.txt[query]
使用可能なプレースホルダー: [file]
、[query]
、[filebase]
(Webpack 5では[base]
)。
抽出されたコメントが保存されるファイル。デフォルトでは、元のファイル名に.LICENSE.txt
サフィックスを追加します。
警告
txt
拡張子の使用を強く推奨します。js
/cjs
/mjs
拡張子を使用すると、既存のアセットと競合し、コードが壊れる可能性があります。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
extractComments: {
condition: /^\**!|@preserve|@license|@cc_on/i,
filename: "extracted-comments.js",
banner: (licenseFile) => {
return `License information can be found in ${licenseFile}`;
},
},
}),
],
},
};
banner
型
type banner = string | boolean | ((commentsFile: string) => string) | undefined;
デフォルト: /*! For license information please see ${commentsFile} */
抽出されたファイルを指すバナーテキストで、元のファイルの先頭に追加されます。false
(バナーなし)、String
、または抽出されたコメントが保存されたファイル名で呼び出されるFunction<(string) -> String>
にすることができます。コメントでラップされます。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
extractComments: {
condition: true,
filename: (fileData) => {
// The "fileData" argument contains object with "filename", "basename", "query" and "hash"
return `${fileData.filename}.LICENSE.txt${fileData.query}`;
},
banner: (commentsFile) => {
return `My custom banner about license information ${commentsFile}`;
},
},
}),
],
},
};
すべての法的コメント(つまり、/^\**!|@preserve|@license|@cc_on/i
)を抽出し、/@license/i
コメントを保持します。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
format: {
comments: /@license/i,
},
},
extractComments: true,
}),
],
},
};
コメントを使用してビルドしない場合は、この設定を使用してください。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
format: {
comments: false,
},
},
extractComments: false,
}),
],
},
};
uglify-js
UglifyJS
は、JavaScriptパーサー、ミニファイア、コンプレッサー、ビューティファイアツールキットです。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
minify: TerserPlugin.uglifyJsMinify,
// `terserOptions` options will be passed to `uglify-js`
// Link to options - https://github.com/mishoo/UglifyJS#minify-options
terserOptions: {},
}),
],
},
};
swc
swc
はRustで記述された超高速コンパイラで、最新の標準とTypeScriptから広くサポートされているJavaScriptを生成します。
警告
extractComments
オプションはサポートされておらず、デフォルトですべてのコメントが削除されます。これは将来修正されます。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
minify: TerserPlugin.swcMinify,
// `terserOptions` options will be passed to `swc` (`@swc/core`)
// Link to options - https://swc.dokyumento.jp/docs/config-js-minify
terserOptions: {},
}),
],
},
};
esbuild
esbuild
は非常に高速なJavaScriptバンドラーおよびミニファイアです。
警告
extractComments
オプションはサポートされておらず、すべての法的コメント(著作権、ライセンスなど)が保持されます。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
minify: TerserPlugin.esbuildMinify,
// `terserOptions` options will be passed to `esbuild`
// Link to options - https://esbuild.dokyumento.jp/api/#minify
// Note: the `minify` options is true by default (and override other `minify*` options), so if you want to disable the `minifyIdentifiers` option (or other `minify*` options) please use:
// terserOptions: {
// minify: false,
// minifyWhitespace: true,
// minifyIdentifiers: false,
// minifySyntax: true,
// },
terserOptions: {},
}),
],
},
};
デフォルトのminify関数をオーバーライドします - minificationにuglify-js
を使用します。
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
minify: (file, sourceMap) => {
// https://github.com/mishoo/UglifyJS2#minify-options
const uglifyJsOptions = {
/* your `uglify-js` package options */
};
if (sourceMap) {
uglifyJsOptions.sourceMap = {
content: sourceMap,
};
}
return require("uglify-js").minify(file, uglifyJsOptions);
},
}),
],
},
};
デフォルトのterser minify関数を使用
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
compress: true,
},
}),
],
},
};
組み込みのminify関数を使用
import type { JsMinifyOptions as SwcOptions } from "@swc/core";
import type { MinifyOptions as UglifyJSOptions } from "uglify-js";
import type { TransformOptions as EsbuildOptions } from "esbuild";
import type { MinifyOptions as TerserOptions } from "terser";
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin<SwcOptions>({
minify: TerserPlugin.swcMinify,
terserOptions: {
// `swc` options
},
}),
new TerserPlugin<UglifyJSOptions>({
minify: TerserPlugin.uglifyJsMinify,
terserOptions: {
// `uglif-js` options
},
}),
new TerserPlugin<EsbuildOptions>({
minify: TerserPlugin.esbuildMinify,
terserOptions: {
// `esbuild` options
},
}),
// Alternative usage:
new TerserPlugin<TerserOptions>({
minify: TerserPlugin.terserMinify,
terserOptions: {
// `terser` options
},
}),
],
},
};
まだお読みでない場合は、コントリビューションガイドラインをお読みください。