This commit is contained in:
2022-07-18 02:50:52 +00:00
parent befd344ab0
commit 06181b34d6
8569 changed files with 818704 additions and 352705 deletions
+100 -14
View File
@@ -16,9 +16,9 @@ var _serializeJavascript = _interopRequireDefault(require("serialize-javascript"
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class Webpack4Cache {
constructor(compiler, compilation, options) {
this.options = options;
this.cacheDir = options.cache === true ? Webpack4Cache.getCacheDirectory() : options.cache;
constructor(compilation, options, weakCache) {
this.cache = options.cache === true ? Webpack4Cache.getCacheDirectory() : options.cache;
this.weakCache = weakCache;
}
static getCacheDirectory() {
@@ -27,20 +27,106 @@ class Webpack4Cache {
}) || _os.default.tmpdir();
}
isEnabled() {
return !!this.cacheDir;
async get(cacheData, {
RawSource,
ConcatSource,
SourceMapSource
}) {
if (!this.cache) {
// eslint-disable-next-line no-undefined
return undefined;
}
const weakOutput = this.weakCache.get(cacheData.inputSource);
if (weakOutput) {
return weakOutput;
} // eslint-disable-next-line no-param-reassign
cacheData.cacheIdent = cacheData.cacheIdent || (0, _serializeJavascript.default)(cacheData.cacheKeys);
let cachedResult;
try {
cachedResult = await _cacache.default.get(this.cache, cacheData.cacheIdent);
} catch (ignoreError) {
// eslint-disable-next-line no-undefined
return undefined;
}
cachedResult = JSON.parse(cachedResult.data);
if (cachedResult.target === 'comments') {
return new ConcatSource(cachedResult.value);
}
const {
code,
name,
map,
input,
inputSourceMap,
extractedComments,
banner,
shebang
} = cachedResult;
if (map) {
cachedResult.source = new SourceMapSource(code, name, map, input, inputSourceMap, true);
} else {
cachedResult.source = new RawSource(code);
}
if (banner) {
cachedResult.source = new ConcatSource(shebang ? `${shebang}\n` : '', `/*! ${banner} */\n`, cachedResult.source);
}
if (extractedComments) {
cachedResult.extractedCommentsSource = new RawSource(extractedComments);
}
return cachedResult;
}
get(task) {
// eslint-disable-next-line no-param-reassign
task.cacheIdent = task.cacheIdent || (0, _serializeJavascript.default)(task.cacheKeys);
return _cacache.default.get(this.cacheDir, task.cacheIdent).then(({
data
}) => JSON.parse(data));
}
async store(cacheData) {
if (!this.cache) {
// eslint-disable-next-line no-undefined
return undefined;
}
store(task, data) {
return _cacache.default.put(this.cacheDir, task.cacheIdent, JSON.stringify(data));
if (!this.weakCache.has(cacheData.inputSource)) {
if (cacheData.target === 'comments') {
this.weakCache.set(cacheData.inputSource, cacheData.output);
} else {
this.weakCache.set(cacheData.inputSource, cacheData);
}
}
let data;
if (cacheData.target === 'comments') {
data = {
target: cacheData.target,
value: cacheData.output.source()
};
} else {
data = {
code: cacheData.code,
name: cacheData.name,
map: cacheData.map,
input: cacheData.input,
inputSourceMap: cacheData.inputSourceMap,
banner: cacheData.banner,
shebang: cacheData.shebang
};
if (cacheData.extractedCommentsSource) {
data.extractedComments = cacheData.extractedCommentsSource.source();
data.commentsFilename = cacheData.commentsFilename;
}
}
return _cacache.default.put(this.cache, cacheData.cacheIdent, JSON.stringify(data));
}
}
+17 -62
View File
@@ -5,76 +5,31 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = void 0;
var _getLazyHashedEtag = _interopRequireDefault(require("webpack/lib/cache/getLazyHashedEtag"));
var _serializeJavascript = _interopRequireDefault(require("serialize-javascript"));
var _webpack = require("webpack");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// eslint-disable-next-line import/extensions,import/no-unresolved
class Cache {
constructor(compiler, compilation, options) {
this.compiler = compiler;
this.compilation = compilation;
this.options = options;
constructor(compilation) {
this.cache = compilation.getCache('TerserWebpackPlugin');
}
isEnabled() {
return !!this.compilation.cache;
async get(cacheData) {
// eslint-disable-next-line no-param-reassign
cacheData.eTag = cacheData.eTag || Array.isArray(cacheData.inputSource) ? cacheData.inputSource.map(item => this.cache.getLazyHashedEtag(item)).reduce((previousValue, currentValue) => this.cache.mergeEtags(previousValue, currentValue)) : this.cache.getLazyHashedEtag(cacheData.inputSource);
return this.cache.getPromise(cacheData.name, cacheData.eTag);
}
createCacheIdent(task) {
const {
outputOptions: {
hashSalt,
hashDigest,
hashDigestLength,
hashFunction
}
} = this.compilation;
async store(cacheData) {
let data;
const hash = _webpack.util.createHash(hashFunction);
if (hashSalt) {
hash.update(hashSalt);
if (cacheData.target === 'comments') {
data = cacheData.output;
} else {
data = {
source: cacheData.source,
extractedCommentsSource: cacheData.extractedCommentsSource,
commentsFilename: cacheData.commentsFilename
};
}
hash.update((0, _serializeJavascript.default)(task.cacheKeys));
const digest = hash.digest(hashDigest);
const cacheKeys = digest.substr(0, hashDigestLength);
return `${this.compilation.compilerPath}/TerserWebpackPlugin/${cacheKeys}/${task.file}`;
}
get(task) {
// eslint-disable-next-line no-param-reassign
task.cacheIdent = task.cacheIdent || this.createCacheIdent(task); // eslint-disable-next-line no-param-reassign
task.cacheETag = task.cacheETag || (0, _getLazyHashedEtag.default)(task.asset);
return new Promise((resolve, reject) => {
this.compilation.cache.get(task.cacheIdent, task.cacheETag, (err, result) => {
if (err) {
reject(err);
} else if (result) {
resolve(result);
} else {
reject();
}
});
});
}
store(task, data) {
return new Promise((resolve, reject) => {
this.compilation.cache.store(task.cacheIdent, task.cacheETag, data, err => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
return this.cache.storePromise(cacheData.name, cacheData.eTag, data);
}
}
+422 -283
View File
@@ -7,40 +7,52 @@ exports.default = void 0;
var _path = _interopRequireDefault(require("path"));
var _os = _interopRequireDefault(require("os"));
var _sourceMap = require("source-map");
var _webpackSources = require("webpack-sources");
var _webpack = _interopRequireWildcard(require("webpack"));
var _RequestShortener = _interopRequireDefault(require("webpack/lib/RequestShortener"));
var _webpack = require("webpack");
var _schemaUtils = _interopRequireDefault(require("schema-utils"));
var _schemaUtils = require("schema-utils");
var _serializeJavascript = _interopRequireDefault(require("serialize-javascript"));
var _package = _interopRequireDefault(require("terser/package.json"));
var _pLimit = _interopRequireDefault(require("p-limit"));
var _jestWorker = _interopRequireDefault(require("jest-worker"));
var _options = _interopRequireDefault(require("./options.json"));
var _TaskRunner = _interopRequireDefault(require("./TaskRunner"));
var _minify = require("./minify");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const warningRegex = /\[.+:([0-9]+),([0-9]+)\]/;
// webpack 5 exposes the sources property to ensure the right version of webpack-sources is used
const {
SourceMapSource,
RawSource,
ConcatSource
} = // eslint-disable-next-line global-require
_webpack.default.sources || require('webpack-sources');
class TerserPlugin {
constructor(options = {}) {
(0, _schemaUtils.default)(_options.default, options, {
(0, _schemaUtils.validate)(_options.default, options, {
name: 'Terser Plugin',
baseDataPath: 'options'
});
const {
minify,
terserOptions = {},
test = /\.m?js(\?.*)?$/i,
chunkFilter = () => true,
warningsFilter = () => true,
test = /\.[cm]?js(\?.*)?$/i,
extractComments = true,
sourceMap,
cache = true,
@@ -51,8 +63,6 @@ class TerserPlugin {
} = options;
this.options = {
test,
chunkFilter,
warningsFilter,
extractComments,
sourceMap,
cache,
@@ -71,16 +81,7 @@ class TerserPlugin {
return Boolean(input && input.version && input.sources && Array.isArray(input.sources) && typeof input.mappings === 'string');
}
static buildSourceMap(inputSourceMap) {
if (!inputSourceMap || !TerserPlugin.isSourceMap(inputSourceMap)) {
return null;
}
return new _sourceMap.SourceMapConsumer(inputSourceMap);
}
static buildError(error, file, sourceMap, requestShortener) {
// Handling error which should have line, col, filename and message
if (error.line) {
const original = sourceMap && sourceMap.originalPositionFor({
line: error.line,
@@ -101,258 +102,408 @@ class TerserPlugin {
return new Error(`${file} from Terser\n${error.message}`);
}
static buildWarning(warning, file, sourceMap, requestShortener, warningsFilter) {
let warningMessage = warning;
let locationMessage = '';
let source = null;
if (sourceMap) {
const match = warningRegex.exec(warning);
if (match) {
const line = +match[1];
const column = +match[2];
const original = sourceMap.originalPositionFor({
line,
column
});
if (original && original.source && original.source !== file && requestShortener) {
({
source
} = original);
warningMessage = `${warningMessage.replace(warningRegex, '')}`;
locationMessage = `[${requestShortener.shorten(original.source)}:${original.line},${original.column}]`;
}
}
} // Todo change order in next major release
if (warningsFilter && !warningsFilter(warning, source, file)) {
return null;
}
return `Terser Plugin: ${warningMessage}${locationMessage}`;
}
static removeQueryString(filename) {
let targetFilename = filename;
const queryStringIdx = targetFilename.indexOf('?');
if (queryStringIdx >= 0) {
targetFilename = targetFilename.substr(0, queryStringIdx);
}
return targetFilename;
}
static hasAsset(commentFilename, assets) {
const assetFilenames = Object.keys(assets).map(assetFilename => TerserPlugin.removeQueryString(assetFilename));
return assetFilenames.includes(TerserPlugin.removeQueryString(commentFilename));
}
static isWebpack4() {
return _webpack.version[0] === '4';
}
*taskGenerator(compiler, compilation, allExtractedComments, file) {
let inputSourceMap;
const asset = compilation.assets[file];
try {
let input;
if (this.options.sourceMap && asset.sourceAndMap) {
const {
source,
map
} = asset.sourceAndMap();
input = source;
if (TerserPlugin.isSourceMap(map)) {
inputSourceMap = map;
} else {
inputSourceMap = map;
compilation.warnings.push(new Error(`${file} contains invalid source map`));
}
} else {
input = asset.source();
inputSourceMap = null;
} // Handling comment extraction
static getAvailableNumberOfCores(parallel) {
// In some cases cpus() returns undefined
// https://github.com/nodejs/node/issues/19022
const cpus = _os.default.cpus() || {
length: 1
};
return parallel === true ? cpus.length - 1 : Math.min(Number(parallel) || 0, cpus.length - 1);
} // eslint-disable-next-line consistent-return
let commentsFilename = false;
static getAsset(compilation, name) {
// New API
if (compilation.getAsset) {
return compilation.getAsset(name);
}
/* istanbul ignore next */
if (this.options.extractComments) {
commentsFilename = this.options.extractComments.filename || '[file].LICENSE.txt[query]';
if (TerserPlugin.isWebpack4()) {
// Todo remove this in next major release
if (typeof commentsFilename === 'function') {
commentsFilename = commentsFilename.bind(null, file);
}
}
if (compilation.assets[name]) {
return {
name,
source: compilation.assets[name],
info: {}
};
}
}
let query = '';
let filename = file;
const querySplit = filename.indexOf('?');
static emitAsset(compilation, name, source, assetInfo) {
// New API
if (compilation.emitAsset) {
compilation.emitAsset(name, source, assetInfo);
} // eslint-disable-next-line no-param-reassign
if (querySplit >= 0) {
query = filename.substr(querySplit);
filename = filename.substr(0, querySplit);
}
const lastSlashIndex = filename.lastIndexOf('/');
const basename = lastSlashIndex === -1 ? filename : filename.substr(lastSlashIndex + 1);
const data = {
filename,
basename,
query
};
commentsFilename = compilation.getPath(commentsFilename, data);
compilation.assets[name] = source;
}
static updateAsset(compilation, name, newSource, assetInfo) {
// New API
if (compilation.updateAsset) {
compilation.updateAsset(name, newSource, assetInfo);
} // eslint-disable-next-line no-param-reassign
compilation.assets[name] = newSource;
}
async optimize(compiler, compilation, assets, CacheEngine, weakCache) {
let assetNames;
if (TerserPlugin.isWebpack4()) {
assetNames = [].concat(Array.from(compilation.additionalChunkAssets || [])).concat( // In webpack@4 it is `chunks`
Array.from(assets).reduce((acc, chunk) => acc.concat(Array.from(chunk.files || [])), [])).concat(Object.keys(compilation.assets)).filter((assetName, index, existingAssets) => existingAssets.indexOf(assetName) === index).filter(assetName => _webpack.ModuleFilenameHelpers.matchObject.bind( // eslint-disable-next-line no-undefined
undefined, this.options)(assetName));
} else {
assetNames = Object.keys(assets).filter(assetName => _webpack.ModuleFilenameHelpers.matchObject.bind( // eslint-disable-next-line no-undefined
undefined, this.options)(assetName));
}
if (assetNames.length === 0) {
return;
}
const availableNumberOfCores = TerserPlugin.getAvailableNumberOfCores(this.options.parallel);
let concurrency = Infinity;
let worker;
if (availableNumberOfCores > 0) {
// Do not create unnecessary workers when the number of files is less than the available cores, it saves memory
const numWorkers = Math.min(assetNames.length, availableNumberOfCores);
concurrency = numWorkers;
worker = new _jestWorker.default(require.resolve('./minify'), {
numWorkers
}); // https://github.com/facebook/jest/issues/8872#issuecomment-524822081
const workerStdout = worker.getStdout();
if (workerStdout) {
workerStdout.on('data', chunk => {
return process.stdout.write(chunk);
});
}
if (commentsFilename && TerserPlugin.hasAsset(commentsFilename, compilation.assets)) {
// Todo make error and stop uglifing in next major release
compilation.warnings.push(new Error(`The comment file "${TerserPlugin.removeQueryString(commentsFilename)}" conflicts with an existing asset, this may lead to code corruption, please use a different name`));
const workerStderr = worker.getStderr();
if (workerStderr) {
workerStderr.on('data', chunk => {
return process.stderr.write(chunk);
});
}
}
const callback = taskResult => {
let {
code
} = taskResult;
const limit = (0, _pLimit.default)(concurrency);
const cache = new CacheEngine(compilation, {
cache: this.options.cache
}, weakCache);
const allExtractedComments = new Map();
const scheduledTasks = [];
for (const name of assetNames) {
scheduledTasks.push(limit(async () => {
const {
error,
map,
warnings
} = taskResult;
const {
extractedComments
} = taskResult;
let sourceMap = null;
info,
source: inputSource
} = TerserPlugin.getAsset(compilation, name); // Skip double minimize assets from child compilation
if (error || warnings && warnings.length > 0) {
sourceMap = TerserPlugin.buildSourceMap(inputSourceMap);
} // Handling results
// Error case: add errors, and go to next file
if (error) {
compilation.errors.push(TerserPlugin.buildError(error, file, sourceMap, new _RequestShortener.default(compiler.context)));
if (info.minimized) {
return;
}
const hasExtractedComments = commentsFilename && extractedComments && extractedComments.length > 0;
const hasBannerForExtractedComments = hasExtractedComments && this.options.extractComments.banner !== false;
let outputSource;
let shebang;
let input;
let inputSourceMap; // TODO refactor after drop webpack@4, webpack@5 always has `sourceAndMap` on sources
if (hasExtractedComments && hasBannerForExtractedComments && code.startsWith('#!')) {
const firstNewlinePosition = code.indexOf('\n');
shebang = code.substring(0, firstNewlinePosition);
code = code.substring(firstNewlinePosition + 1);
}
if (this.options.sourceMap && inputSource.sourceAndMap) {
const {
source,
map
} = inputSource.sourceAndMap();
input = source;
if (map) {
outputSource = new _webpackSources.SourceMapSource(code, file, map, input, inputSourceMap, true);
} else {
outputSource = new _webpackSources.RawSource(code);
} // Write extracted comments to commentsFilename
if (hasExtractedComments) {
if (!allExtractedComments[commentsFilename]) {
// eslint-disable-next-line no-param-reassign
allExtractedComments[commentsFilename] = [];
} // eslint-disable-next-line no-param-reassign
allExtractedComments[commentsFilename] = allExtractedComments[commentsFilename].concat(extractedComments); // Add a banner to the original file
if (hasBannerForExtractedComments) {
let banner = this.options.extractComments.banner || `For license information please see ${_path.default.relative(_path.default.dirname(file), commentsFilename).replace(/\\/g, '/')}`;
if (typeof banner === 'function') {
banner = banner(commentsFilename);
}
if (banner) {
outputSource = new _webpackSources.ConcatSource(shebang ? `${shebang}\n` : '', `/*! ${banner} */\n`, outputSource);
if (map) {
if (TerserPlugin.isSourceMap(map)) {
inputSourceMap = map;
} else {
inputSourceMap = map;
compilation.warnings.push(new Error(`${name} contains invalid source map`));
}
}
} // Updating assets
// eslint-disable-next-line no-param-reassign
} else {
input = inputSource.source();
inputSourceMap = null;
}
if (Buffer.isBuffer(input)) {
input = input.toString();
}
compilation.assets[file] = outputSource; // Handling warnings
const cacheData = {
name,
inputSource
};
if (warnings && warnings.length > 0) {
warnings.forEach(warning => {
const builtWarning = TerserPlugin.buildWarning(warning, file, sourceMap, new _RequestShortener.default(compiler.context), this.options.warningsFilter);
if (TerserPlugin.isWebpack4()) {
if (this.options.cache) {
const {
outputOptions: {
hashSalt,
hashDigest,
hashDigestLength,
hashFunction
}
} = compilation;
if (builtWarning) {
compilation.warnings.push(builtWarning);
const hash = _webpack.util.createHash(hashFunction);
if (hashSalt) {
hash.update(hashSalt);
}
hash.update(input);
const digest = hash.digest(hashDigest);
cacheData.input = input;
cacheData.inputSourceMap = inputSourceMap;
cacheData.cacheKeys = this.options.cacheKeys({
terser: _package.default.version,
// eslint-disable-next-line global-require
'terser-webpack-plugin': require('../package.json').version,
'terser-webpack-plugin-options': this.options,
name,
contentHash: digest.substr(0, hashDigestLength)
}, name);
}
}
let output = await cache.get(cacheData, {
RawSource,
ConcatSource,
SourceMapSource
});
if (!output) {
const minimizerOptions = {
name,
input,
inputSourceMap,
minify: this.options.minify,
minimizerOptions: this.options.terserOptions,
extractComments: this.options.extractComments
};
if (/\.mjs(\?.*)?$/i.test(name)) {
this.options.terserOptions.module = true;
}
try {
output = await (worker ? worker.transform((0, _serializeJavascript.default)(minimizerOptions)) : (0, _minify.minify)(minimizerOptions));
} catch (error) {
compilation.errors.push(TerserPlugin.buildError(error, name, inputSourceMap && TerserPlugin.isSourceMap(inputSourceMap) ? new _sourceMap.SourceMapConsumer(inputSourceMap) : null, new _RequestShortener.default(compiler.context)));
return;
}
let shebang;
if (this.options.extractComments.banner !== false && output.extractedComments && output.extractedComments.length > 0 && output.code.startsWith('#!')) {
const firstNewlinePosition = output.code.indexOf('\n');
shebang = output.code.substring(0, firstNewlinePosition);
output.code = output.code.substring(firstNewlinePosition + 1);
}
if (output.map) {
output.source = new SourceMapSource(output.code, name, output.map, input, inputSourceMap, true);
} else {
output.source = new RawSource(output.code);
}
let commentsFilename;
if (output.extractedComments && output.extractedComments.length > 0) {
commentsFilename = this.options.extractComments.filename || '[file].LICENSE.txt[query]';
let query = '';
let filename = name;
const querySplit = filename.indexOf('?');
if (querySplit >= 0) {
query = filename.substr(querySplit);
filename = filename.substr(0, querySplit);
}
const lastSlashIndex = filename.lastIndexOf('/');
const basename = lastSlashIndex === -1 ? filename : filename.substr(lastSlashIndex + 1);
const data = {
filename,
basename,
query
};
commentsFilename = compilation.getPath(commentsFilename, data);
output.commentsFilename = commentsFilename;
let banner; // Add a banner to the original file
if (this.options.extractComments.banner !== false) {
banner = this.options.extractComments.banner || `For license information please see ${_path.default.relative(_path.default.dirname(name), commentsFilename).replace(/\\/g, '/')}`;
if (typeof banner === 'function') {
banner = banner(commentsFilename);
}
if (banner) {
output.source = new ConcatSource(shebang ? `${shebang}\n` : '', `/*! ${banner} */\n`, output.source);
output.banner = banner;
output.shebang = shebang;
}
}
const extractedCommentsString = output.extractedComments.sort().join('\n\n');
output.extractedCommentsSource = new RawSource(`${extractedCommentsString}\n`);
}
await cache.store({ ...output,
...cacheData
});
} // TODO `...` required only for webpack@4
const newInfo = { ...info,
minimized: true
};
const {
source,
extractedCommentsSource
} = output; // Write extracted comments to commentsFilename
if (extractedCommentsSource) {
const {
commentsFilename
} = output; // TODO `...` required only for webpack@4
newInfo.related = {
license: commentsFilename,
...info.related
};
allExtractedComments.set(name, {
extractedCommentsSource,
commentsFilename
});
}
};
const task = {
asset,
file,
input,
inputSourceMap,
TerserPlugin.updateAsset(compilation, name, source, newInfo);
}));
}
await Promise.all(scheduledTasks);
if (worker) {
await worker.end();
}
await Array.from(allExtractedComments).sort().reduce(async (previousPromise, [from, value]) => {
const previous = await previousPromise;
const {
commentsFilename,
extractComments: this.options.extractComments,
terserOptions: this.options.terserOptions,
minify: this.options.minify,
callback
};
extractedCommentsSource
} = value;
if (TerserPlugin.isWebpack4()) {
if (previous && previous.commentsFilename === commentsFilename) {
const {
outputOptions: {
hashSalt,
hashDigest,
hashDigestLength,
hashFunction
from: previousFrom,
source: prevSource
} = previous;
const mergedName = `${previousFrom}|${from}`;
const cacheData = {
target: 'comments'
};
if (TerserPlugin.isWebpack4()) {
const {
outputOptions: {
hashSalt,
hashDigest,
hashDigestLength,
hashFunction
}
} = compilation;
const previousHash = _webpack.util.createHash(hashFunction);
const hash = _webpack.util.createHash(hashFunction);
if (hashSalt) {
previousHash.update(hashSalt);
hash.update(hashSalt);
}
} = compilation;
const hash = _webpack.util.createHash(hashFunction);
if (hashSalt) {
hash.update(hashSalt);
}
hash.update(input);
const digest = hash.digest(hashDigest);
if (this.options.cache) {
const defaultCacheKeys = {
terser: _package.default.version,
// eslint-disable-next-line global-require
'terser-webpack-plugin': require('../package.json').version,
'terser-webpack-plugin-options': this.options,
nodeVersion: process.version,
filename: file,
previousHash.update(prevSource.source());
hash.update(extractedCommentsSource.source());
const previousDigest = previousHash.digest(hashDigest);
const digest = hash.digest(hashDigest);
cacheData.cacheKeys = {
mergedName,
previousContentHash: previousDigest.substr(0, hashDigestLength),
contentHash: digest.substr(0, hashDigestLength)
};
task.cacheKeys = this.options.cacheKeys(defaultCacheKeys, file);
cacheData.inputSource = extractedCommentsSource;
} else {
const mergedInputSource = [prevSource, extractedCommentsSource];
cacheData.name = `${commentsFilename}|${mergedName}`;
cacheData.inputSource = mergedInputSource;
}
} else {
task.cacheKeys = {
terser: _package.default.version,
// eslint-disable-next-line global-require
'terser-webpack-plugin': require('../package.json').version,
'terser-webpack-plugin-options': this.options
let output = await cache.get(cacheData, {
ConcatSource
});
if (!output) {
output = new ConcatSource(Array.from(new Set([...prevSource.source().split('\n\n'), ...extractedCommentsSource.source().split('\n\n')])).join('\n\n'));
await cache.store({ ...cacheData,
output
});
}
TerserPlugin.updateAsset(compilation, commentsFilename, output);
return {
commentsFilename,
from: mergedName,
source: output
};
}
yield task;
} catch (error) {
compilation.errors.push(TerserPlugin.buildError(error, file, TerserPlugin.buildSourceMap(inputSourceMap), new _RequestShortener.default(compiler.context)));
const existingAsset = TerserPlugin.getAsset(compilation, commentsFilename);
if (existingAsset) {
return {
commentsFilename,
from: commentsFilename,
source: existingAsset.source
};
}
TerserPlugin.emitAsset(compilation, commentsFilename, extractedCommentsSource);
return {
commentsFilename,
from,
source: extractedCommentsSource
};
}, Promise.resolve());
}
static getEcmaVersion(environment) {
// ES 6th
if (environment.arrowFunction || environment.const || environment.destructuring || environment.forOf || environment.module) {
return 2015;
} // ES 11th
if (environment.bigIntLiteral || environment.dynamicImport) {
return 2020;
}
return 5;
}
apply(compiler) {
@@ -361,73 +512,33 @@ class TerserPlugin {
output,
plugins
} = compiler.options;
this.options.sourceMap = typeof this.options.sourceMap === 'undefined' ? devtool && !devtool.includes('eval') && !devtool.includes('cheap') && (devtool.includes('source-map') || // Todo remove when `webpack@5` support will be dropped
this.options.sourceMap = typeof this.options.sourceMap === 'undefined' ? devtool && !devtool.includes('eval') && !devtool.includes('cheap') && (devtool.includes('source-map') || // Todo remove when `webpack@4` support will be dropped
devtool.includes('sourcemap')) || plugins && plugins.some(plugin => plugin instanceof _webpack.SourceMapDevToolPlugin && plugin.options && plugin.options.columns) : Boolean(this.options.sourceMap);
if (typeof this.options.terserOptions.module === 'undefined' && typeof output.module !== 'undefined') {
this.options.terserOptions.module = output.module;
}
if (typeof this.options.terserOptions.ecma === 'undefined' && typeof output.ecmaVersion !== 'undefined') {
this.options.terserOptions.ecma = output.ecmaVersion;
if (typeof this.options.terserOptions.ecma === 'undefined') {
this.options.terserOptions.ecma = TerserPlugin.getEcmaVersion(output.environment || {});
}
const optimizeFn = async (compilation, chunks) => {
const matchObject = _webpack.ModuleFilenameHelpers.matchObject.bind( // eslint-disable-next-line no-undefined
undefined, this.options);
const files = [].concat(Array.from(compilation.additionalChunkAssets || [])).concat(Array.from(chunks).filter(chunk => this.options.chunkFilter && this.options.chunkFilter(chunk)).reduce((acc, chunk) => acc.concat(Array.from(chunk.files || [])), [])).filter(file => matchObject(file));
if (files.length === 0) {
return Promise.resolve();
}
const CacheEngine = TerserPlugin.isWebpack4() ? // eslint-disable-next-line global-require
require('./Webpack4Cache').default : // eslint-disable-next-line global-require
require('./Webpack5Cache').default;
const allExtractedComments = {};
const taskGenerator = this.taskGenerator.bind(this, compiler, compilation, allExtractedComments);
const taskRunner = new _TaskRunner.default({
taskGenerator,
files,
cache: new CacheEngine(compiler, compilation, this.options),
parallel: this.options.parallel
});
await taskRunner.run();
await taskRunner.exit();
Object.keys(allExtractedComments).forEach(commentsFilename => {
const extractedComments = new Set([...allExtractedComments[commentsFilename].sort()]); // eslint-disable-next-line no-param-reassign
compilation.assets[commentsFilename] = new _webpackSources.RawSource(`${Array.from(extractedComments).join('\n\n')}\n`);
});
return Promise.resolve();
};
const plugin = {
name: this.constructor.name
};
compiler.hooks.compilation.tap(plugin, compilation => {
const pluginName = this.constructor.name;
const weakCache = TerserPlugin.isWebpack4() && (this.options.cache === true || typeof this.options.cache === 'string') ? new WeakMap() : // eslint-disable-next-line no-undefined
undefined;
compiler.hooks.compilation.tap(pluginName, compilation => {
if (this.options.sourceMap) {
compilation.hooks.buildModule.tap(plugin, moduleArg => {
compilation.hooks.buildModule.tap(pluginName, moduleArg => {
// to get detailed location info about errors
// eslint-disable-next-line no-param-reassign
moduleArg.useSourceMap = true;
});
}
if (!TerserPlugin.isWebpack4()) {
const hooks = _webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation);
if (TerserPlugin.isWebpack4()) {
// eslint-disable-next-line global-require
const CacheEngine = require('./Webpack4Cache').default;
const data = (0, _serializeJavascript.default)({
terser: _package.default.version,
terserOptions: this.options.terserOptions
});
hooks.chunkHash.tap(plugin, (chunk, hash) => {
hash.update('TerserPlugin');
hash.update(data);
});
} else {
// Todo remove after drop `webpack@4` compatibility
const {
mainTemplate,
chunkTemplate
@@ -438,14 +549,42 @@ class TerserPlugin {
}); // Regenerate `contenthash` for minified assets
for (const template of [mainTemplate, chunkTemplate]) {
template.hooks.hashForChunk.tap(plugin, hash => {
template.hooks.hashForChunk.tap(pluginName, hash => {
hash.update('TerserPlugin');
hash.update(data);
});
}
}
compilation.hooks.optimizeChunkAssets.tapPromise(plugin, optimizeFn.bind(this, compilation));
compilation.hooks.optimizeChunkAssets.tapPromise(pluginName, assets => this.optimize(compiler, compilation, assets, CacheEngine, weakCache));
} else {
// eslint-disable-next-line global-require
const CacheEngine = require('./Webpack5Cache').default; // eslint-disable-next-line global-require
const Compilation = require('webpack/lib/Compilation');
const hooks = _webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation);
const data = (0, _serializeJavascript.default)({
terser: _package.default.version,
terserOptions: this.options.terserOptions
});
hooks.chunkHash.tap(pluginName, (chunk, hash) => {
hash.update('TerserPlugin');
hash.update(data);
});
compilation.hooks.processAssets.tapPromise({
name: pluginName,
stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE
}, assets => this.optimize(compiler, compilation, assets, CacheEngine));
compilation.hooks.statsPrinter.tap(pluginName, stats => {
stats.hooks.print.for('asset.info.minimized').tap('terser-webpack-plugin', (minimized, {
green,
formatFlag
}) => // eslint-disable-next-line no-undefined
minimized ? green(formatFlag('minimized')) : undefined);
});
}
});
}
+35 -34
View File
@@ -6,7 +6,6 @@ const {
const buildTerserOptions = ({
ecma,
warnings,
parse = {},
compress = {},
mangle,
@@ -23,8 +22,6 @@ const buildTerserOptions = ({
/* eslint-enable camelcase */
safari10
} = {}) => ({
ecma,
warnings,
parse: { ...parse
},
compress: typeof compress === 'boolean' ? compress : { ...compress
@@ -36,15 +33,16 @@ const buildTerserOptions = ({
beautify: false,
...output
},
module,
// Ignoring sourceMap from options
sourceMap: null,
toplevel,
nameCache,
ie8,
ecma,
keep_classnames,
keep_fnames,
safari10
ie8,
module,
nameCache,
safari10,
toplevel
});
function isObject(value) {
@@ -52,13 +50,12 @@ function isObject(value) {
return value != null && (type === 'object' || type === 'function');
}
const buildComments = (options, terserOptions, extractedComments) => {
const buildComments = (extractComments, terserOptions, extractedComments) => {
const condition = {};
const commentsOpts = terserOptions.output.comments;
const {
extractComments
} = options;
condition.preserve = typeof commentsOpts !== 'undefined' ? commentsOpts : false;
comments
} = terserOptions.output;
condition.preserve = typeof comments !== 'undefined' ? comments : false;
if (typeof extractComments === 'boolean' && extractComments) {
condition.extract = 'some';
@@ -71,7 +68,7 @@ const buildComments = (options, terserOptions, extractedComments) => {
} else {
// No extract
// Preserve using "commentsOpts" or "some"
condition.preserve = typeof commentsOpts !== 'undefined' ? commentsOpts : 'some';
condition.preserve = typeof comments !== 'undefined' ? comments : 'some';
condition.extract = false;
} // Ensure that both conditions are functions
@@ -133,22 +130,23 @@ const buildComments = (options, terserOptions, extractedComments) => {
};
};
const minify = options => {
async function minify(options) {
const {
file,
name,
input,
inputSourceMap,
minify: minifyFn
minify: minifyFn,
minimizerOptions
} = options;
if (minifyFn) {
return minifyFn({
[file]: input
}, inputSourceMap);
[name]: input
}, inputSourceMap, minimizerOptions);
} // Copy terser options
const terserOptions = buildTerserOptions(options.terserOptions); // Let terser generate a SourceMap
const terserOptions = buildTerserOptions(minimizerOptions); // Let terser generate a SourceMap
if (inputSourceMap) {
terserOptions.sourceMap = {
@@ -157,22 +155,25 @@ const minify = options => {
}
const extractedComments = [];
terserOptions.output.comments = buildComments(options, terserOptions, extractedComments);
const {
error,
map,
code,
warnings
} = terserMinify({
[file]: input
extractComments
} = options;
terserOptions.output.comments = buildComments(extractComments, terserOptions, extractedComments);
const result = await terserMinify({
[name]: input
}, terserOptions);
return {
error,
map,
code,
warnings,
return { ...result,
extractedComments
};
};
}
module.exports = minify;
function transform(options) {
// 'use strict' => this === undefined (Clean Scope)
// Safer for possible security issues, albeit not critical at all here
// eslint-disable-next-line no-new-func, no-param-reassign
options = new Function('exports', 'require', 'module', '__filename', '__dirname', `'use strict'\nreturn ${options}`)(exports, require, module, __filename, __dirname);
return minify(options);
}
module.exports.minify = minify;
module.exports.transform = transform;
+45 -48
View File
@@ -1,73 +1,68 @@
{
"additionalProperties": false,
"definitions": {
"file-conditions": {
"Rule": {
"description": "Filtering rule as regex or string.",
"anyOf": [
{
"instanceof": "RegExp"
"instanceof": "RegExp",
"tsType": "RegExp"
},
{
"type": "string"
"type": "string",
"minLength": 1
}
]
},
"Rules": {
"description": "Filtering rules.",
"anyOf": [
{
"type": "array",
"items": {
"description": "A rule condition.",
"oneOf": [
{
"$ref": "#/definitions/Rule"
}
]
}
},
{
"$ref": "#/definitions/Rule"
}
]
}
},
"title": "TerserPluginOptions",
"type": "object",
"additionalProperties": false,
"properties": {
"test": {
"anyOf": [
"description": "Include all modules that pass test assertion.",
"oneOf": [
{
"$ref": "#/definitions/file-conditions"
},
{
"items": {
"anyOf": [
{
"$ref": "#/definitions/file-conditions"
}
]
},
"type": "array"
"$ref": "#/definitions/Rules"
}
]
},
"include": {
"anyOf": [
"description": "Include all modules matching any of these conditions.",
"oneOf": [
{
"$ref": "#/definitions/file-conditions"
},
{
"items": {
"anyOf": [
{
"$ref": "#/definitions/file-conditions"
}
]
},
"type": "array"
"$ref": "#/definitions/Rules"
}
]
},
"exclude": {
"anyOf": [
"description": "Exclude all modules matching any of these conditions.",
"oneOf": [
{
"$ref": "#/definitions/file-conditions"
},
{
"items": {
"anyOf": [
{
"$ref": "#/definitions/file-conditions"
}
]
},
"type": "array"
"$ref": "#/definitions/Rules"
}
]
},
"chunkFilter": {
"instanceof": "Function"
},
"cache": {
"description": "Enable file caching. Ignored in webpack 5, for webpack 5 please use https://webpack.js.org/configuration/other-options/#cache.",
"anyOf": [
{
"type": "boolean"
@@ -78,9 +73,11 @@
]
},
"cacheKeys": {
"description": "Allows you to override default cache keys. Ignored in webpack 5, for webpack 5 please use https://webpack.js.org/configuration/other-options/#cache.",
"instanceof": "Function"
},
"parallel": {
"description": "Use multi-process parallel running to improve the build speed.",
"anyOf": [
{
"type": "boolean"
@@ -91,16 +88,20 @@
]
},
"sourceMap": {
"description": "Enables/Disables generation of source maps.",
"type": "boolean"
},
"minify": {
"description": "Allows you to override default minify function.",
"instanceof": "Function"
},
"terserOptions": {
"description": "Options for `terser`.",
"additionalProperties": true,
"type": "object"
},
"extractComments": {
"description": "Whether comments shall be extracted to a separate file.",
"anyOf": [
{
"type": "boolean"
@@ -160,10 +161,6 @@
"type": "object"
}
]
},
"warningsFilter": {
"instanceof": "Function"
}
},
"type": "object"
}
}