You're Invited:Meet the Socket Team at RSAC and BSidesSF 2026, March 23–26.RSVP
Socket
Book a DemoSign in
Socket

css-minimizer-webpack-plugin

Package Overview
Dependencies
Maintainers
3
Versions
37
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

css-minimizer-webpack-plugin - npm Package Compare versions

Comparing version
7.0.2
to
7.0.3
+102
-118
dist/index.js
"use strict";
const os = require("os");
const os = require("node:os");
const {

@@ -8,16 +8,16 @@ validate

const {
throttleAll,
memoize,
minify
} = require("./minify");
const schema = require("./options.json");
const {
cleanCssMinify,
cssnanoMinify,
cssoMinify,
cleanCssMinify,
esbuildMinify,
lightningCssMinify,
memoize,
parcelCssMinify,
lightningCssMinify,
swcMinify
swcMinify,
throttleAll
} = require("./utils");
const schema = require("./options.json");
const {
minify: minifyWorker
} = require("./minify");

@@ -29,3 +29,3 @@ /** @typedef {import("schema-utils/declarations/validate").Schema} Schema */

/** @typedef {import("jest-worker").Worker} JestWorker */
/** @typedef {import("@jridgewell/trace-mapping").EncodedSourceMap} RawSourceMap */
/** @typedef {import("@jridgewell/trace-mapping").EncodedSourceMap & { sources: string[], sourcesContent?: string[], file: string }} RawSourceMap */
/** @typedef {import("webpack").Asset} Asset */

@@ -39,5 +39,5 @@ /** @typedef {import("postcss").ProcessOptions} ProcessOptions */

/**
* @typedef {Object} CssNanoOptions
* @property {string} [configFile]
* @property {[string, object] | string | undefined} [preset]
* @typedef {Record<string, unknown>} CssNanoOptions
* @property {string=} configFile Configuration file path
* @property {string | [string, Record<string, unknown>] | undefined=} preset CSS nano preset
*/

@@ -48,24 +48,24 @@

/**
* @typedef {Object} WarningObject
* @property {string} message
* @property {string} [plugin]
* @property {string} [text]
* @property {number} [line]
* @property {number} [column]
* @typedef {object} WarningObject
* @property {string} message Warning message
* @property {string=} plugin Plugin name
* @property {string=} text Warning text
* @property {number=} line Line number
* @property {number=} column Column number
*/
/**
* @typedef {Object} ErrorObject
* @property {string} message
* @property {number} [line]
* @property {number} [column]
* @property {string} [stack]
* @typedef {object} ErrorObject
* @property {string} message Error message
* @property {number=} line Line number
* @property {number=} column Column number
* @property {string=} stack Error stack trace
*/
/**
* @typedef {Object} MinimizedResult
* @property {string} code
* @property {RawSourceMap} [map]
* @property {Array<Error | ErrorObject| string>} [errors]
* @property {Array<Warning | WarningObject | string>} [warnings]
* @typedef {object} MinimizedResult
* @property {string} code Minimized code
* @property {RawSourceMap=} map Source map
* @property {Array<Error | ErrorObject| string>=} errors Errors
* @property {Array<Warning | WarningObject | string>=} warnings Warnings
*/

@@ -78,3 +78,3 @@

/**
* @typedef {{ [key: string]: any }} CustomOptions
* @typedef {{ [key: string]: unknown }} CustomOptions
*/

@@ -103,3 +103,3 @@

* @typedef {object} MinimizeFunctionHelpers
* @property {() => boolean | undefined} [supportsWorkerThreads]
* @property {() => boolean | undefined=} supportsWorkerThreads Check if worker threads are supported
*/

@@ -114,7 +114,7 @@

* @template T
* @typedef {Object} InternalOptions
* @property {string} name
* @property {string} input
* @property {RawSourceMap | undefined} inputSourceMap
* @property {{ implementation: MinimizerImplementation<T>, options: MinimizerOptions<T> }} minimizer
* @typedef {object} InternalOptions
* @property {string} name Name
* @property {string} input Input
* @property {RawSourceMap | undefined} inputSourceMap Input source map
* @property {{ implementation: MinimizerImplementation<T>, options: MinimizerOptions<T> }} minimizer Minimizer
*/

@@ -124,5 +124,5 @@

* @typedef InternalResult
* @property {Array<{ code: string, map: RawSourceMap | undefined }>} outputs
* @property {Array<Warning | WarningObject | string>} warnings
* @property {Array<Error | ErrorObject | string>} errors
* @property {Array<{ code: string, map: RawSourceMap | undefined }>} outputs - Outputs
* @property {Array<Warning | WarningObject | string>} warnings - Warnings
* @property {Array<Error | ErrorObject | string>} errors - Errors
*/

@@ -138,8 +138,8 @@

/**
* @typedef {Object} BasePluginOptions
* @property {Rule} [test]
* @property {Rule} [include]
* @property {Rule} [exclude]
* @property {WarningsFilter} [warningsFilter]
* @property {Parallel} [parallel]
* @typedef {object} BasePluginOptions
* @property {Rule=} test Test rule
* @property {Rule=} include Include rule
* @property {Rule=} exclude Exclude rule
* @property {WarningsFilter=} warningsFilter Warnings filter
* @property {Parallel=} parallel Parallel option
*/

@@ -149,7 +149,7 @@

* @template T
* @typedef {JestWorker & { transform: (options: string) => InternalResult, minify: (options: InternalOptions<T>) => InternalResult }} MinimizerWorker
* @typedef {JestWorker & { transform: (options: string) => Promise<InternalResult>, minify: (options: InternalOptions<T>) => Promise<InternalResult> }} MinimizerWorker
*/
/**
* @typedef{ProcessOptions | { from?: string, to?: string, parser?: string | Syntax | Parser, stringifier?: string | Syntax | Stringifier, syntax?: string | Syntax } } ProcessOptionsExtender
* @typedef {ProcessOptions | { from?: string, to?: string, parser?: string | Syntax | Parser, stringifier?: string | Syntax | Stringifier, syntax?: string | Syntax } } ProcessOptionsExtender
*/

@@ -172,8 +172,4 @@

const warningRegex = /\s.+:+([0-9]+):+([0-9]+)/;
const getSerializeJavascript = memoize(() =>
// eslint-disable-next-line global-require
require("serialize-javascript"));
const getTraceMapping = memoize(() =>
// eslint-disable-next-line global-require
require("@jridgewell/trace-mapping"));
const getSerializeJavascript = memoize(() => require("serialize-javascript"));
const getTraceMapping = memoize(() => require("@jridgewell/trace-mapping"));

@@ -185,6 +181,6 @@ /**

/**
* @param {BasePluginOptions & DefinedDefaultMinimizerAndOptions<T>} [options]
* @param {BasePluginOptions & DefinedDefaultMinimizerAndOptions<T>=} options Plugin options
*/
constructor(options) {
validate( /** @type {Schema} */schema, options || {}, {
validate(/** @type {Schema} */schema, options || {}, {
name: "Css Minimizer Plugin",

@@ -194,4 +190,4 @@ baseDataPath: "options"

const {
minify = ( /** @type {BasicMinimizerImplementation<T>} */cssnanoMinify),
minimizerOptions = ( /** @type {MinimizerOptions<T>} */{}),
minify = (/** @type {BasicMinimizerImplementation<T>} */cssnanoMinify),
minimizerOptions = (/** @type {MinimizerOptions<T>} */{}),
test = /\.css(\?.*)?$/i,

@@ -215,3 +211,3 @@ warningsFilter = () => true,

minimizer: {
implementation: ( /** @type {MinimizerImplementation<T>} */minify),
implementation: (/** @type {MinimizerImplementation<T>} */minify),
options: minimizerOptions

@@ -224,4 +220,4 @@ }

* @private
* @param {any} input
* @returns {boolean}
* @param {unknown} input Input to check
* @returns {boolean} Whether input is a source map
*/

@@ -231,3 +227,3 @@ static isSourceMap(input) {

// https://github.com/mozilla/source-map#new-sourcemapconsumerrawsourcemap
return Boolean(input && input.version && input.sources && Array.isArray(input.sources) && typeof input.mappings === "string");
return Boolean(input && typeof input === "object" && input !== null && "version" in input && "sources" in input && Array.isArray(input.sources) && "mappings" in input && typeof input.mappings === "string");
}

@@ -237,8 +233,8 @@

* @private
* @param {Warning | WarningObject | string} warning
* @param {string} file
* @param {WarningsFilter} [warningsFilter]
* @param {TraceMap} [sourceMap]
* @param {Compilation["requestShortener"]} [requestShortener]
* @returns {Error & { hideStack?: boolean, file?: string } | undefined}
* @param {Warning | WarningObject | string} warning Warning
* @param {string} file File name
* @param {WarningsFilter=} warningsFilter Warnings filter
* @param {TraceMap=} sourceMap Source map
* @param {Compilation["requestShortener"]=} requestShortener Request shortener
* @returns {Error & { hideStack?: boolean, file?: string } | undefined} Built warning
*/

@@ -255,4 +251,4 @@ static buildWarning(warning, file, warningsFilter, sourceMap, requestShortener) {

if (match) {
line = +match[1];
column = +match[2];
line = Number(match[1]);
column = Number(match[2]);
}

@@ -290,4 +286,2 @@ } else {

builtWarning.file = file;
// eslint-disable-next-line consistent-return
return builtWarning;

@@ -298,7 +292,7 @@ }

* @private
* @param {Error | ErrorObject | string} error
* @param {string} file
* @param {TraceMap} [sourceMap]
* @param {Compilation["requestShortener"]} [requestShortener]
* @returns {Error}
* @param {Error | ErrorObject | string} error Error
* @param {string} file File name
* @param {TraceMap=} sourceMap Source map
* @param {Compilation["requestShortener"]=} requestShortener Request shortener
* @returns {Error} Built error
*/

@@ -315,3 +309,3 @@ static buildError(error, file, sourceMap, requestShortener) {

}
if ( /** @type {ErrorObject} */error.line && /** @type {ErrorObject} */error.column) {
if (/** @type {ErrorObject} */error.line && /** @type {ErrorObject} */error.column) {
const {

@@ -346,4 +340,4 @@ line,

* @private
* @param {Parallel} parallel
* @returns {number}
* @param {Parallel} parallel Parallel option
* @returns {number} Available number of cores
*/

@@ -353,3 +347,8 @@ static getAvailableNumberOfCores(parallel) {

// https://github.com/nodejs/node/issues/19022
const cpus = typeof os.availableParallelism === "function" ? {
const cpus =
// eslint-disable-next-line n/no-unsupported-features/node-builtins
typeof os.availableParallelism === "function" ?
// eslint-disable-next-line n/no-unsupported-features/node-builtins
{
length: os.availableParallelism()

@@ -365,4 +364,4 @@ } : os.cpus() || {

* @template T
* @param {BasicMinimizerImplementation<T> & MinimizeFunctionHelpers} implementation
* @returns {boolean}
* @param {BasicMinimizerImplementation<T> & MinimizeFunctionHelpers} implementation Implementation
* @returns {boolean} Whether worker threads are supported
*/

@@ -375,7 +374,7 @@ static isSupportsWorkerThreads(implementation) {

* @private
* @param {Compiler} compiler
* @param {Compilation} compilation
* @param {Record<string, import("webpack").sources.Source>} assets
* @param {{availableNumberOfCores: number}} optimizeOptions
* @returns {Promise<void>}
* @param {Compiler} compiler Compiler
* @param {Compilation} compilation Compilation
* @param {Record<string, import("webpack").sources.Source>} assets Assets
* @param {{availableNumberOfCores: number}} optimizeOptions Optimize options
* @returns {Promise<void>} Promise
*/

@@ -394,5 +393,3 @@ async optimize(compiler, compilation, assets, optimizeOptions) {

}
if (!compiler.webpack.ModuleFilenameHelpers.matchObject.bind(
// eslint-disable-next-line no-undefined
undefined, this.options)(name)) {
if (!compiler.webpack.ModuleFilenameHelpers.matchObject.bind(undefined, this.options)(name)) {
return false;

@@ -438,4 +435,2 @@ }

}
// eslint-disable-next-line global-require
const {

@@ -488,3 +483,3 @@ Worker

if (!CssMinimizerPlugin.isSourceMap(map)) {
compilation.warnings.push( /** @type {WebpackError} */
compilation.warnings.push(/** @type {WebpackError} */
new Error(`${name} contains invalid source map`));

@@ -513,11 +508,7 @@ } else {

try {
result = await (getWorker ? getWorker().transform(getSerializeJavascript()(options)) : minifyWorker(options));
result = await (getWorker ? getWorker().transform(getSerializeJavascript()(options)) : minify(options));
} catch (error) {
const hasSourceMap = inputSourceMap && CssMinimizerPlugin.isSourceMap(inputSourceMap);
compilation.errors.push( /** @type {WebpackError} */
CssMinimizerPlugin.buildError( /** @type {any} */error, name, hasSourceMap ? new (getTraceMapping().TraceMap)( /** @type {RawSourceMap} */inputSourceMap) :
// eslint-disable-next-line no-undefined
undefined,
// eslint-disable-next-line no-undefined
hasSourceMap ? compilation.requestShortener : undefined));
compilation.errors.push(/** @type {WebpackError} */
CssMinimizerPlugin.buildError(/** @type {Error} */error, name, hasSourceMap ? new (getTraceMapping().TraceMap)(/** @type {RawSourceMap} */inputSourceMap) : undefined, hasSourceMap ? compilation.requestShortener : undefined));
return;

@@ -545,3 +536,3 @@ }

output.source = new SourceMapSource(item.code, name, item.map, originalSource, innerSourceMap, true);
} else {
} else if (item.code) {
output.source = new RawSource(item.code);

@@ -553,7 +544,3 @@ }

for (const error of result.errors) {
output.warnings.push(CssMinimizerPlugin.buildError(error, name, hasSourceMap ? new (getTraceMapping().TraceMap)( /** @type {RawSourceMap} */inputSourceMap) :
// eslint-disable-next-line no-undefined
undefined,
// eslint-disable-next-line no-undefined
hasSourceMap ? compilation.requestShortener : undefined));
output.errors.push(CssMinimizerPlugin.buildError(error, name, hasSourceMap ? new (getTraceMapping().TraceMap)(/** @type {RawSourceMap} */inputSourceMap) : undefined, hasSourceMap ? compilation.requestShortener : undefined));
}

@@ -564,7 +551,3 @@ }

for (const warning of result.warnings) {
const buildWarning = CssMinimizerPlugin.buildWarning(warning, name, this.options.warningsFilter, hasSourceMap ? new (getTraceMapping().TraceMap)( /** @type {RawSourceMap} */inputSourceMap) :
// eslint-disable-next-line no-undefined
undefined,
// eslint-disable-next-line no-undefined
hasSourceMap ? compilation.requestShortener : undefined);
const buildWarning = CssMinimizerPlugin.buildWarning(warning, name, this.options.warningsFilter, hasSourceMap ? new (getTraceMapping().TraceMap)(/** @type {RawSourceMap} */inputSourceMap) : undefined, hasSourceMap ? compilation.requestShortener : undefined);
if (buildWarning) {

@@ -591,2 +574,5 @@ output.warnings.push(buildWarning);

}
if (!output.source) {
return;
}
const newInfo = {

@@ -601,3 +587,3 @@ minimized: true

}
const limit = getWorker && numberOfAssetsForMinify > 0 ? ( /** @type {number} */numberOfWorkers) : scheduledTasks.length;
const limit = getWorker && numberOfAssetsForMinify > 0 ? (/** @type {number} */numberOfWorkers) : scheduledTasks.length;
await throttleAll(limit, scheduledTasks);

@@ -610,4 +596,4 @@ if (initializedWorker) {

/**
* @param {Compiler} compiler
* @returns {void}
* @param {Compiler} compiler Compiler
* @returns {void} Void
*/

@@ -629,5 +615,3 @@ apply(compiler) {

formatFlag
}) =>
// eslint-disable-next-line no-undefined
minimized ? /** @type {Function} */green( /** @type {Function} */formatFlag("minimized")) : "");
}) => minimized ? /** @type {(text: string) => string} */green(/** @type {(flag: string) => string} */formatFlag("minimized")) : "");
});

@@ -634,0 +618,0 @@ });

@@ -8,6 +8,6 @@ "use strict";

* @template T
* @param {import("./index.js").InternalOptions<T>} options
* @returns {Promise<InternalResult>}
* @param {import("./index.js").InternalOptions<T>} options Options
* @returns {Promise<InternalResult>} Promise with internal result
*/
const minify = async options => {
async function minify(options) {
const minifyFns = Array.isArray(options.minimizer.implementation) ? options.minimizer.implementation : [options.minimizer.implementation];

@@ -33,3 +33,2 @@

} = prevResult;
// eslint-disable-next-line no-await-in-loop
const minifyResult = await minifyFn({

@@ -39,3 +38,3 @@ [options.name]: code

if (typeof minifyResult.code !== "string") {
throw new Error("minimizer function doesn't return the 'code' property or result is not a string value");
result.errors.push(new Error("minimizer function doesn't return the 'code' property or result is not a string value"));
}

@@ -46,6 +45,6 @@ if (minifyResult.map) {

if (minifyResult.errors) {
result.errors = result.errors.concat(minifyResult.errors);
result.errors = [...result.errors, ...minifyResult.errors];
}
if (minifyResult.warnings) {
result.warnings = result.warnings.concat(minifyResult.warnings);
result.warnings = [...result.warnings, ...minifyResult.warnings];
}

@@ -61,7 +60,7 @@ result.outputs.push({

return result;
};
}
/**
* @param {string} options
* @returns {Promise<InternalResult>}
* @param {string} options Options string
* @returns {Promise<InternalResult>} Promise with internal result
*/

@@ -71,4 +70,4 @@ async function transform(options) {

// Safer for possible security issues, albeit not critical at all here
// eslint-disable-next-line no-new-func, no-param-reassign
const evaluatedOptions = new Function("exports", "require", "module", "__filename", "__dirname", `'use strict'\nreturn ${options}`)(exports, require, module, __filename, __dirname);
// eslint-disable-next-line no-new-func
const evaluatedOptions = new Function("exports", "require", "module", "__filename", "__dirname", `'use strict'\nreturn ${options}`)(module.exports, require, module, __filename, __dirname);
return minify(evaluatedOptions);

@@ -75,0 +74,0 @@ }

@@ -45,3 +45,3 @@ {

"description": "Include all modules that pass test assertion.",
"link": "https://github.com/webpack-contrib/css-minimizer-webpack-plugin/#test",
"link": "https://github.com/webpack/css-minimizer-webpack-plugin/#test",
"oneOf": [

@@ -55,3 +55,3 @@ {

"description": "Include all modules matching any of these conditions.",
"link": "https://github.com/webpack-contrib/css-minimizer-webpack-plugin/#include",
"link": "https://github.com/webpack/css-minimizer-webpack-plugin/#include",
"oneOf": [

@@ -65,3 +65,3 @@ {

"description": "Exclude all modules matching any of these conditions.",
"link": "https://github.com/webpack-contrib/css-minimizer-webpack-plugin/#exclude",
"link": "https://github.com/webpack/css-minimizer-webpack-plugin/#exclude",
"oneOf": [

@@ -75,3 +75,3 @@ {

"description": "Options for `cssMinimizerOptions`.",
"link": "https://github.com/webpack-contrib/css-minimizer-webpack-plugin/#minimizeroptions",
"link": "https://github.com/webpack/css-minimizer-webpack-plugin/#minimizeroptions",
"anyOf": [

@@ -92,3 +92,3 @@ {

"description": "Use multi-process parallel running to improve the build speed.",
"link": "https://github.com/webpack-contrib/css-minimizer-webpack-plugin/#parallel",
"link": "https://github.com/webpack/css-minimizer-webpack-plugin/#parallel",
"anyOf": [

@@ -105,3 +105,3 @@ {

"description": "Allow to filter `css minimizer` warnings.",
"link": "https://github.com/webpack-contrib/css-minimizer-webpack-plugin/#warningsfilter",
"link": "https://github.com/webpack/css-minimizer-webpack-plugin/#warningsfilter",
"instanceof": "Function"

@@ -111,3 +111,3 @@ },

"description": "Allows you to override default minify function.",
"link": "https://github.com/webpack-contrib/css-minimizer-webpack-plugin/#minify",
"link": "https://github.com/webpack/css-minimizer-webpack-plugin/#minify",
"anyOf": [

@@ -114,0 +114,0 @@ {

"use strict";
/** @typedef {import("./index.js").Input} Input */
/** @typedef {import("@jridgewell/trace-mapping").EncodedSourceMap} RawSourceMap */
/** @typedef {import("./index.js").RawSourceMap} RawSourceMap */
/** @typedef {import("./index.js").MinimizedResult} MinimizedResult */

@@ -10,3 +10,3 @@ /** @typedef {import("./index.js").CustomOptions} CustomOptions */

const notSettled = Symbol(`not-settled`);
const notSettled = Symbol("not-settled");

@@ -21,4 +21,4 @@ /**

* @template T
* @param {number} limit - Limit of tasks that run at once.
* @param {Task<T>[]} tasks - List of tasks to run.
* @param {number} limit Limit of tasks that run at once.
* @param {Task<T>[]} tasks List of tasks to run.
* @returns {Promise<T[]>} A promise that fulfills to an array of the results

@@ -30,7 +30,9 @@ */

}
if (!Array.isArray(tasks) || !tasks.every(task => typeof task === `function`)) {
throw new TypeError(`Expected \`tasks\` to be a list of functions returning a promise`);
if (!Array.isArray(tasks) || !tasks.every(task => typeof task === "function")) {
throw new TypeError("Expected `tasks` to be a list of functions returning a promise");
}
return new Promise((resolve, reject) => {
const result = Array(tasks.length).fill(notSettled);
const result = Array.from({
length: tasks.length
}).fill(notSettled);
const entries = tasks.entries();

@@ -50,6 +52,6 @@ const next = () => {

/**
* @param {T} x
* @param {T} resultValue Result value
*/
const onFulfilled = x => {
result[index] = x;
const onFulfilled = resultValue => {
result[index] = resultValue;
next();

@@ -59,3 +61,5 @@ };

};
Array(limit).fill(0).forEach(next);
for (let i = 0; i < limit; i++) {
next();
}
});

@@ -66,6 +70,6 @@ }

/**
* @param {Input} input
* @param {RawSourceMap | undefined} sourceMap
* @param {CustomOptions} [minimizerOptions]
* @return {Promise<MinimizedResult>}
* @param {Input} input Input
* @param {RawSourceMap=} sourceMap Source map
* @param {CustomOptions=} minimizerOptions Minimizer options
* @returns {Promise<MinimizedResult>} Promise with minimized result
*/

@@ -77,4 +81,4 @@ async function cssnanoMinify(input, sourceMap, minimizerOptions = {

* @template T
* @param {string} module
* @returns {Promise<T>}
* @param {string} module Module to load
* @returns {Promise<T>} Promise with loaded module
*/

@@ -84,6 +88,5 @@ const load = async module => {

try {
// eslint-disable-next-line import/no-dynamic-require, global-require
exports = require(module);
return exports;
} catch (requireError) {
} catch (err) {
let importESM;

@@ -93,11 +96,11 @@ try {

importESM = new Function("id", "return import(id);");
} catch (e) {
} catch {
importESM = null;
}
if ( /** @type {Error & {code: string}} */
requireError.code === "ERR_REQUIRE_ESM" && importESM) {
if (/** @type {Error & {code: string}} */
err.code === "ERR_REQUIRE_ESM" && importESM) {
exports = await importESM(module);
return exports.default;
}
throw requireError;
throw err;
}

@@ -109,3 +112,3 @@ };

from: name,
...minimizerOptions.processorOptions
...(minimizerOptions.processorOptions && typeof minimizerOptions.processorOptions === "object" ? minimizerOptions.processorOptions : {})
};

@@ -140,8 +143,6 @@ if (typeof postcssOptions.parser === "string") {

/** @type {Postcss} */
// eslint-disable-next-line global-require
const postcss = require("postcss").default;
// @ts-ignore
// eslint-disable-next-line global-require
const cssnano = require("cssnano");
// @ts-ignore
// Types are broken

@@ -151,6 +152,4 @@ const result = await postcss([cssnano(minimizerOptions)]).process(code, postcssOptions);

code: result.css,
// @ts-ignore
map: result.map ? result.map.toJSON() :
// eslint-disable-next-line no-undefined
undefined,
map: result.map ? (/** @type {RawSourceMap} */
/** @type {unknown} */result.map.toJSON()) : undefined,
warnings: result.warnings().map(String)

@@ -163,9 +162,8 @@ };

/**
* @param {Input} input
* @param {RawSourceMap | undefined} sourceMap
* @param {CustomOptions} [minimizerOptions]
* @return {Promise<MinimizedResult>}
* @param {Input} input Input
* @param {RawSourceMap=} sourceMap Source map
* @param {CustomOptions=} minimizerOptions Minimizer options
* @returns {Promise<MinimizedResult>} Promise with minimized result
*/
async function cssoMinify(input, sourceMap, minimizerOptions) {
// eslint-disable-next-line global-require,import/no-extraneous-dependencies
const csso = require("csso");

@@ -180,6 +178,4 @@ const [[filename, code]] = Object.entries(input);

code: result.css,
map: result.map ? /** @type {any & { toJSON(): RawSourceMap }} */
result.map.toJSON() :
// eslint-disable-next-line no-undefined
undefined
map: result.map ? (/** @type {RawSourceMap} */
/** @type {{ toJSON(): RawSourceMap }} */result.map.toJSON()) : undefined
};

@@ -191,9 +187,8 @@ }

/**
* @param {Input} input
* @param {RawSourceMap | undefined} sourceMap
* @param {CustomOptions} [minimizerOptions]
* @return {Promise<MinimizedResult>}
* @param {Input} input Input
* @param {RawSourceMap=} sourceMap Source map
* @param {CustomOptions=} minimizerOptions Minimizer options
* @returns {Promise<MinimizedResult>} Promise with minimized result
*/
async function cleanCssMinify(input, sourceMap, minimizerOptions) {
// eslint-disable-next-line global-require,import/no-extraneous-dependencies
const CleanCSS = require("clean-css");

@@ -210,15 +205,15 @@ const [[name, code]] = Object.entries(input);

});
const generatedSourceMap = result.sourceMap && /** @type {any & { toJSON(): RawSourceMap }} */
result.sourceMap.toJSON();
const generatedSourceMap = result.sourceMap ? (/** @type {RawSourceMap} */
// eslint-disable-next-line jsdoc/no-restricted-syntax
/** @type {any} */result.sourceMap.toJSON()) : undefined;
// workaround for source maps on windows
if (generatedSourceMap) {
// eslint-disable-next-line global-require
const isWindowsPathSep = require("path").sep === "\\";
const isWindowsPathSep = require("node:path").sep === "\\";
generatedSourceMap.sources = generatedSourceMap.sources.map(
/**
* @param {string} item
* @returns {string}
* @param {string | null} item Path item
* @returns {string} Normalized path
*/
item => isWindowsPathSep ? item.replace(/\\/g, "/") : item);
item => isWindowsPathSep ? (item || "").replaceAll("\\", "/") : item || "");
}

@@ -235,24 +230,21 @@ return {

/**
* @param {Input} input
* @param {RawSourceMap | undefined} sourceMap
* @param {CustomOptions} [minimizerOptions]
* @return {Promise<MinimizedResult>}
* @param {Input} input Input
* @param {RawSourceMap=} sourceMap Source map
* @param {CustomOptions=} minimizerOptions Minimizer options
* @returns {Promise<MinimizedResult>} Promise with minimized result
*/
async function esbuildMinify(input, sourceMap, minimizerOptions) {
/**
* @param {import("esbuild").TransformOptions} [esbuildOptions={}]
* @returns {import("esbuild").TransformOptions}
* @param {import("esbuild").TransformOptions=} esbuildOptions ESBuild options
* @returns {import("esbuild").TransformOptions} Built ESBuild options
*/
const buildEsbuildOptions = (esbuildOptions = {}) => {
// Need deep copy objects to avoid https://github.com/terser/terser/issues/366
return {
loader: "css",
minify: true,
legalComments: "inline",
...esbuildOptions,
sourcemap: false
};
};
// eslint-disable-next-line import/no-extraneous-dependencies, global-require
const buildEsbuildOptions = (esbuildOptions = {}) => (
// Need deep copy objects to avoid https://github.com/terser/terser/issues/366
{
loader: "css",
minify: true,
legalComments: "inline",
...esbuildOptions,
sourcemap: false
});
const esbuild = require("esbuild");

@@ -273,17 +265,10 @@

code: result.code,
// eslint-disable-next-line no-undefined
map: result.map ? JSON.parse(result.map) : undefined,
warnings: result.warnings.length > 0 ? result.warnings.map(item => {
return {
source: item.location && item.location.file,
line: item.location && item.location.line ? item.location.line :
// eslint-disable-next-line no-undefined
undefined,
column: item.location && item.location.column ? item.location.column :
// eslint-disable-next-line no-undefined
undefined,
plugin: item.pluginName,
message: `${item.text}${item.detail ? `\nDetails:\n${item.detail}` : ""}${item.notes.length > 0 ? `\n\nNotes:\n${item.notes.map(note => `${note.location ? `[${note.location.file}:${note.location.line}:${note.location.column}] ` : ""}${note.text}${note.location ? `\nSuggestion: ${note.location.suggestion}` : ""}${note.location ? `\nLine text:\n${note.location.lineText}\n` : ""}`).join("\n")}` : ""}`
};
}) : []
warnings: result.warnings.length > 0 ? result.warnings.map(item => ({
source: item.location && item.location.file,
line: item.location && item.location.line ? item.location.line : undefined,
column: item.location && item.location.column ? item.location.column : undefined,
plugin: item.pluginName,
message: `${item.text}${item.detail ? `\nDetails:\n${item.detail}` : ""}${item.notes.length > 0 ? `\n\nNotes:\n${item.notes.map(note => `${note.location ? `[${note.location.file}:${note.location.line}:${note.location.column}] ` : ""}${note.text}${note.location ? `\nSuggestion: ${note.location.suggestion}` : ""}${note.location ? `\nLine text:\n${note.location.lineText}\n` : ""}`).join("\n")}` : ""}`
})) : []
};

@@ -296,25 +281,23 @@ }

/**
* @param {Input} input
* @param {RawSourceMap | undefined} sourceMap
* @param {CustomOptions} [minimizerOptions]
* @return {Promise<MinimizedResult>}
* @param {Input} input Input
* @param {RawSourceMap=} sourceMap Source map
* @param {CustomOptions=} minimizerOptions Minimizer options
* @returns {Promise<MinimizedResult>} Promise with minimized result
*/
async function parcelCssMinify(input, sourceMap, minimizerOptions) {
const [[filename, code]] = Object.entries(input);
// eslint-disable-next-line jsdoc/no-restricted-syntax
/**
* @param {Partial<import("@parcel/css").TransformOptions<any>>} [parcelCssOptions={}]
* @returns {import("@parcel/css").TransformOptions<any>}
* @param {Partial<import("@parcel/css").TransformOptions<any>>=} parcelCssOptions Parcel CSS options
* @returns {import("@parcel/css").TransformOptions<any>} Built Parcel CSS options
*/
const buildParcelCssOptions = (parcelCssOptions = {}) => {
// Need deep copy objects to avoid https://github.com/terser/terser/issues/366
return {
minify: true,
...parcelCssOptions,
sourceMap: false,
filename,
code: Buffer.from(code)
};
};
// eslint-disable-next-line import/no-extraneous-dependencies, global-require
const buildParcelCssOptions = (parcelCssOptions = {}) => (
// Need deep copy objects to avoid https://github.com/terser/terser/issues/366
{
minify: true,
...parcelCssOptions,
sourceMap: false,
filename,
code: new Uint8Array(Buffer.from(code))
});
const parcelCss = require("@parcel/css");

@@ -332,3 +315,2 @@

code: result.code.toString(),
// eslint-disable-next-line no-undefined
map: result.map ? JSON.parse(result.map.toString()) : undefined

@@ -341,25 +323,23 @@ };

/**
* @param {Input} input
* @param {RawSourceMap | undefined} sourceMap
* @param {CustomOptions} [minimizerOptions]
* @return {Promise<MinimizedResult>}
* @param {Input} input Input
* @param {RawSourceMap=} sourceMap Source map
* @param {CustomOptions=} minimizerOptions Minimizer options
* @returns {Promise<MinimizedResult>} Promise with minimized result
*/
async function lightningCssMinify(input, sourceMap, minimizerOptions) {
const [[filename, code]] = Object.entries(input);
// eslint-disable-next-line jsdoc/no-restricted-syntax
/**
* @param {Partial<import("lightningcss").TransformOptions<any>>} [lightningCssOptions={}]
* @returns {import("lightningcss").TransformOptions<any>}
* @param {Partial<import("lightningcss").TransformOptions<any>>=} lightningCssOptions Lightning CSS options
* @returns {import("lightningcss").TransformOptions<any>} Built Lightning CSS options
*/
const buildLightningCssOptions = (lightningCssOptions = {}) => {
// Need deep copy objects to avoid https://github.com/terser/terser/issues/366
return {
minify: true,
...lightningCssOptions,
sourceMap: false,
filename,
code: Buffer.from(code)
};
};
// eslint-disable-next-line import/no-extraneous-dependencies, global-require
const buildLightningCssOptions = (lightningCssOptions = {}) => (
// Need deep copy objects to avoid https://github.com/terser/terser/issues/366
{
minify: true,
...lightningCssOptions,
sourceMap: false,
filename,
code: new Uint8Array(Buffer.from(code))
});
const lightningCss = require("lightningcss");

@@ -377,3 +357,2 @@

code: result.code.toString(),
// eslint-disable-next-line no-undefined
map: result.map ? JSON.parse(result.map.toString()) : undefined

@@ -386,6 +365,6 @@ };

/**
* @param {Input} input
* @param {RawSourceMap | undefined} sourceMap
* @param {CustomOptions} [minimizerOptions]
* @return {Promise<MinimizedResult>}
* @param {Input} input Input
* @param {RawSourceMap=} sourceMap Source map
* @param {CustomOptions=} minimizerOptions Minimizer options
* @returns {Promise<MinimizedResult>} Promise with minimized result
*/

@@ -395,14 +374,11 @@ async function swcMinify(input, sourceMap, minimizerOptions) {

/**
* @param {Partial<import("@swc/css").MinifyOptions>} [swcOptions={}]
* @returns {import("@swc/css").MinifyOptions}
* @param {Partial<import("@swc/css").MinifyOptions>=} swcOptions SWC options
* @returns {import("@swc/css").MinifyOptions} Built SWC options
*/
const buildSwcOptions = (swcOptions = {}) => {
// Need deep copy objects to avoid https://github.com/terser/terser/issues/366
return {
...swcOptions,
filename
};
};
// eslint-disable-next-line import/no-extraneous-dependencies, global-require
const buildSwcOptions = (swcOptions = {}) => (
// Need deep copy objects to avoid https://github.com/terser/terser/issues/366
{
...swcOptions,
filename
});
const swc = require("@swc/css");

@@ -420,3 +396,2 @@

code: result.code.toString(),
// eslint-disable-next-line no-undefined
map: result.map ? JSON.parse(result.map.toString()) : undefined,

@@ -426,10 +401,11 @@ errors: result.errors ? result.errors.map(diagnostic => {

// @ts-ignore
// eslint-disable-next-line jsdoc/no-restricted-syntax
/** @type {any} */
error.span = diagnostic.span;
// @ts-ignore
// eslint-disable-next-line jsdoc/no-restricted-syntax
/** @type {any} */
error.level = diagnostic.level;
return error;
}) :
// eslint-disable-next-line no-undefined
undefined
}) : undefined
};

@@ -441,4 +417,4 @@ }

* @template T
* @param fn {(function(): any) | undefined}
* @returns {function(): T}
* @param {(() => unknown) | undefined} fn Function to memoize
* @returns {() => T} Memoized function
*/

@@ -453,7 +429,7 @@ function memoize(fn) {

}
result = /** @type {function(): any} */fn();
result = /** @type {T} */ /** @type {() => unknown} */fn();
cache = true;
// Allow to clean up memory for fn
// and all dependent resources
// eslint-disable-next-line no-undefined, no-param-reassign
fn = undefined;

@@ -464,11 +440,11 @@ return result;

module.exports = {
throttleAll,
memoize,
cleanCssMinify,
cssnanoMinify,
cssoMinify,
cleanCssMinify,
esbuildMinify,
lightningCssMinify,
memoize,
parcelCssMinify,
lightningCssMinify,
swcMinify
swcMinify,
throttleAll
};
{
"name": "css-minimizer-webpack-plugin",
"version": "7.0.2",
"version": "7.0.3",
"description": "CSS minimizer (minifier) plugin for Webpack",
"license": "MIT",
"repository": "webpack-contrib/css-minimizer-webpack-plugin",
"author": "Loann Neveu",
"homepage": "https://github.com/webpack-contrib/css-minimizer-webpack-plugin",
"bugs": "https://github.com/webpack-contrib/css-minimizer-webpack-plugin/issues",
"keywords": [
"cssnano",
"css",
"csso",
"clean-css",
"swc",
"esbuild",
"webpack",
"webpack-plugin",
"minimize",
"minimizer",
"minify",
"minifier",
"optimize",
"optimizer"
],
"homepage": "https://github.com/webpack/css-minimizer-webpack-plugin",
"bugs": "https://github.com/webpack/css-minimizer-webpack-plugin/issues",
"repository": "webpack/css-minimizer-webpack-plugin",
"funding": {

@@ -14,7 +28,10 @@ "type": "opencollective",

},
"license": "MIT",
"author": "Loann Neveu",
"main": "dist/index.js",
"types": "types/index.d.ts",
"engines": {
"node": ">= 18.12.0"
},
"files": [
"dist",
"types"
],
"scripts": {

@@ -27,12 +44,12 @@ "start": "npm run build -- -w",

"build": "npm-run-all -p \"build:**\"",
"commitlint": "commitlint --from=master",
"commitlint": "commitlint --from=main",
"security": "npm audit",
"lint:prettier": "prettier --cache --list-different .",
"lint:js": "eslint --cache .",
"lint:code": "eslint --cache .",
"lint:spelling": "cspell --cache --no-must-find-files --quiet \"**/*.*\"",
"lint:types": "tsc --pretty --noEmit",
"lint": "npm-run-all -l -p \"lint:**\"",
"fix:js": "npm run lint:js -- --fix",
"fix:code": "npm run lint:code -- --fix",
"fix:prettier": "npm run lint:prettier -- --write",
"fix": "npm-run-all -l fix:js fix:prettier",
"fix": "npm-run-all -l fix:code fix:prettier",
"test:only": "cross-env NODE_ENV=test NODE_OPTIONS=\"--experimental-vm-modules\" jest",

@@ -46,33 +63,6 @@ "test:watch": "npm run test:only -- --watch",

},
"files": [
"dist",
"types"
],
"peerDependencies": {
"webpack": "^5.0.0"
},
"peerDependenciesMeta": {
"clean-css": {
"optional": true
},
"csso": {
"optional": true
},
"esbuild": {
"optional": true
},
"@parcel/css": {
"optional": true
},
"lightningcss": {
"optional": true
},
"@swc/css": {
"optional": true
}
},
"dependencies": {
"@jridgewell/trace-mapping": "^0.3.25",
"cssnano": "^7.0.4",
"jest-worker": "^29.7.0",
"jest-worker": "^30.0.5",
"postcss": "^8.4.40",

@@ -88,3 +78,6 @@ "schema-utils": "^4.2.0",

"@commitlint/config-conventional": "^19.2.2",
"@eslint/js": "^9.32.0",
"@eslint/markdown": "^7.0.0",
"@parcel/css": "^1.8.3",
"@stylistic/eslint-plugin": "^5.2.2",
"@swc/css": "^0.0.28",

@@ -95,6 +88,5 @@ "@types/clean-css": "^4.2.11",

"@types/serialize-javascript": "^5.0.4",
"@webpack-contrib/eslint-config-webpack": "^3.0.0",
"babel-jest": "^29.7.0",
"babel-jest": "^30.0.5",
"clean-css": "^5.3.3",
"copy-webpack-plugin": "^9.1.0",
"copy-webpack-plugin": "^13.0.0",
"cross-env": "^7.0.3",

@@ -108,7 +100,14 @@ "cspell": "^8.13.1",

"esbuild": "^0.25.0",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-import": "^2.29.1",
"eslint": "^9.30.1",
"eslint-config-prettier": "^10.1.5",
"eslint-config-webpack": "^4.4.1",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-jest": "^29.0.1",
"eslint-plugin-jsdoc": "^52.0.0",
"eslint-plugin-n": "^17.21.0",
"eslint-plugin-prettier": "^5.5.3",
"eslint-plugin-unicorn": "^60.0.0",
"globals": "^16.3.0",
"husky": "^9.1.4",
"jest": "^29.7.0",
"jest": "^30.0.5",
"lightningcss": "^1.25.1",

@@ -119,26 +118,36 @@ "lint-staged": "^15.2.8",

"npm-run-all": "^4.1.5",
"prettier": "^3.3.3",
"prettier": "^3.6.2",
"sass": "^1.77.8",
"sass-loader": "^14.2.1",
"sass-loader": "^16.0.5",
"standard-version": "^9.5.0",
"sugarss": "^4.0.1",
"sugarss": "^5.0.0",
"typescript": "^5.5.4",
"webpack": "^5.93.0"
},
"keywords": [
"cssnano",
"css",
"csso",
"clean-css",
"swc",
"esbuild",
"webpack",
"webpack-plugin",
"minimize",
"minimizer",
"minify",
"minifier",
"optimize",
"optimizer"
]
"peerDependencies": {
"webpack": "^5.0.0"
},
"peerDependenciesMeta": {
"clean-css": {
"optional": true
},
"csso": {
"optional": true
},
"esbuild": {
"optional": true
},
"@parcel/css": {
"optional": true
},
"lightningcss": {
"optional": true
},
"@swc/css": {
"optional": true
}
},
"engines": {
"node": ">= 18.12.0"
}
}
+74
-63

@@ -18,3 +18,3 @@ <div align="center">

Just like [optimize-css-assets-webpack-plugin](https://github.com/NMFR/optimize-css-assets-webpack-plugin) but more accurate with source maps and assets using query string, allows caching and works in parallel mode.
It serves as a more accurate alternative to [optimize-css-assets-webpack-plugin](https://github.com/NMFR/optimize-css-assets-webpack-plugin), with better support for source maps, assets with query strings, caching, and parallel processing.

@@ -46,4 +46,4 @@ ## Getting Started

```js
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

@@ -54,3 +54,3 @@ module.exports = {

{
test: /.s?css$/,
test: /\.s?css$/,
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],

@@ -62,4 +62,3 @@ },

minimizer: [
// For webpack@5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
// `...`,
// For webpack v5, you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line // `...`,
new CssMinimizerPlugin(),

@@ -72,5 +71,7 @@ ],

This will enable CSS optimization only in production mode.
> [!NOTE]
>
> This enables CSS optimization only in production mode by default.
If you want to run it also in development set the `optimization.minimize` option to `true`:
To enable it in development mode as well, set the `optimization.minimize` option to `true`:

@@ -89,17 +90,20 @@ **webpack.config.js**

And run `webpack` via your preferred method.
Finally, run Webpack using your preferred method.
## Note about source maps
**Works only with `source-map`, `inline-source-map`, `hidden-source-map` and `nosources-source-map` values for the [`devtool`](https://webpack.js.org/configuration/devtool/) option.**
**This plugin works only with `source-map`, `inline-source-map`, `hidden-source-map` and `nosources-source-map` values for the [`devtool`](https://webpack.js.org/configuration/devtool/) option.**
Why? Because CSS support only these source map types.
The plugin respect the [`devtool`](https://webpack.js.org/configuration/devtool/) and using the `SourceMapDevToolPlugin` plugin.
Using supported `devtool` values enable source map generation.
Using `SourceMapDevToolPlugin` with enabled the `columns` option enables source map generation.
The plugin respects the [`devtool`](https://webpack.js.org/configuration/devtool/) setting and uses the `SourceMapDevToolPlugin` internally.
Use source maps to map error message locations to modules (this slows down the compilation).
If you use your own `minify` function please read the `minify` section for handling source maps correctly.
Using a supported `devtool` value enables source map generation.
Enabling the `columns` option in `SourceMapDevToolPlugin` also allows source map generation.
Use source maps to map error message locations to their original modules (note that this may slow down compilation).
If you use your own `minify` function please refer to the `minify` section for correct handling of source maps.
## Options

@@ -112,10 +116,11 @@

| **[`exclude`](#exclude)** | `String\|RegExp\|Array<String\|RegExp>` | `undefined` | Files to exclude. |
| **[`parallel`](#parallel)** | `Boolean\|Number` | `true` | Enable/disable multi-process parallel running. |
| **[`parallel`](#parallel)** | `Boolean\|Number` | `true` | Enable or disable multi-process parallel running. |
| **[`minify`](#minify)** | `Function\|Array<Function>` | `CssMinimizerPlugin.cssnanoMinify` | Allows to override default minify function. |
| **[`minimizerOptions`](#minimizeroptions)** | `Object\|Array<Object>` | `{ preset: 'default' }` | Cssnano optimisations [options](https://cssnano.github.io/cssnano/docs/what-are-optimisations/). |
| **[`warningsFilter`](#warningsfilter)** | `Function<(warning, file, source) -> Boolean>` | `() => true` | Allow to filter css-minimizer warnings. |
| **[`warningsFilter`](#warningsfilter)** | `Function<(warning, file, source) -> Boolean>` | `() => true` | Allows filtering of css-minimizer warnings. |
### `test`
Type: `String|RegExp|Array<String|RegExp>` - default: `/\.css(\?.*)?$/i`
- Type: `String|RegExp|Array<String|RegExp>`
- Default: `/\.css(\?.*)?$/i`

@@ -139,4 +144,4 @@ Test to match files against.

Type: `String|RegExp|Array<String|RegExp>`
Default: `undefined`
- Type: `String|RegExp|Array<String|RegExp>`
- Default: `undefined`

@@ -162,4 +167,4 @@ Files to include.

Type: `String|RegExp|Array<String|RegExp>`
Default: `undefined`
- Type: `String|RegExp|Array<String|RegExp>`
- Default: `undefined`

@@ -185,8 +190,9 @@ Files to exclude.

Type: `Boolean|Number`
Default: `true`
- Type: `Boolean|Number`
- Default: `true`
Use multi-process parallel running to improve the build speed.
Default number of concurrent runs: `os.cpus().length - 1` or `os.availableParallelism() - 1` (if this function is supported).
The default number of concurrent runs: `os.cpus().length - 1` or `os.availableParallelism() - 1` (if this function is supported).
> ℹ️ Parallelization can speed up your build significantly and is therefore **highly recommended**.

@@ -197,3 +203,3 @@ > If a parallelization is enabled, the packages in `minimizerOptions` must be required via strings (`packageName` or `require.resolve(packageName)`). Read more in [`minimizerOptions`](#minimizeroptions)

Enable/disable multi-process parallel running.
Enable or disable multi-process parallel running.

@@ -217,3 +223,3 @@ **webpack.config.js**

Enable multi-process parallel running and set number of concurrent runs.
Enable multi-process parallel running and specify the number of concurrent runs.

@@ -237,9 +243,11 @@ **webpack.config.js**

Type: `Function|Array<Function>`
Default: `CssMinimizerPlugin.cssnanoMinify`
- Type: `Function|Array<Function>`
- Default: `CssMinimizerPlugin.cssnanoMinify`
Allows overriding default minify function.
Overrides the default minify function.
By default, plugin uses [cssnano](https://github.com/cssnano/cssnano) package.
Useful for using and testing unpublished versions or forks.
> This is useful when using or testing unpublished versions or forks.
Possible options:

@@ -256,3 +264,3 @@

>
> **Always use `require` inside `minify` function when `parallel` option enabled**.
> **Always use `require` inside `minify` function when `parallel` option is enabled**.

@@ -286,2 +294,3 @@ #### `Function`

If an array of functions is passed to the `minify` option, the `minimizerOptions` must also be an array.
The function index in the `minify` array corresponds to the options object with the same index in the `minimizerOptions` array.

@@ -298,4 +307,4 @@

minimizerOptions: [
{}, // Options for the first function (CssMinimizerPlugin.cssnanoMinify)
{}, // Options for the second function (CssMinimizerPlugin.cleanCssMinify)
{}, // Options for the first function (CssMinimizerPlugin.cssnanoMinify),
{}, // Options for the second function (CssMinimizerPlugin.cleanCssMinify),
{}, // Options for the third function

@@ -306,11 +315,10 @@ ],

CssMinimizerPlugin.cleanCssMinify,
async (data, inputMap, minimizerOptions) => {
// To do something
return {
code: `a{color: red}`,
map: `{"version": "3", ...}`,
async (data, inputMap, minimizerOptions) =>
// Custom minifier function
({
code: "a{color: red}",
map: '{"version": "3", ...}',
warnings: [],
errors: [],
};
},
}),
],

@@ -325,4 +333,4 @@ }),

Type: `Object|Array<Object>`
Default: `{ preset: 'default' }`
- Type: `Object|Array<Object>`
- Default: `{ preset: 'default' }`

@@ -356,5 +364,6 @@ Cssnano optimisations [options](https://cssnano.co/docs/what-are-optimisations/).

The function index in the `minify` array corresponds to the options object with the same index in the `minimizerOptions` array.
If you use `minimizerOptions` like object, all `minify` function accept it.
> If a parallelization is enabled, the packages in `minimizerOptions` must be required via strings (`packageName` or `require.resolve(packageName)`). In this case, we shouldn't use `require`/`import`.
> If parallelization is enabled, the packages in `minimizerOptions` must be referenced via strings (`packageName` or `require.resolve(packageName)`). In this case, we shouldn't use `require`/`import`.

@@ -378,6 +387,7 @@ ```js

Type: `Object`
Default: `{ from: assetName }`
- Type: `Object`
- Default: `{ from: assetName }`
Allows filtering options [`processoptions`](https://postcss.org/api/#processoptions) for the cssnano.
The `parser`,` stringifier` and `syntax` can be either a function or a string indicating the module that will be imported.

@@ -387,3 +397,3 @@

>
> **If a function is passed, the `parallel` option must be disabled.**.
> **If any of these options are passed as a function, the `parallel` option must be disabled.**.

@@ -429,11 +439,12 @@ ```js

Type: `Function<(warning, file, source) -> Boolean>`
Default: `() => true`
- Type: `Function<(warning, file, source) -> Boolean>`
- Default: `() => true`
Allow filtering css-minimizer warnings (By default [cssnano](https://github.com/cssnano/cssnano)).
Return `true` to keep the warning, a falsy value (`false`/`null`/`undefined`) otherwise.
Filter css-minimizer warnings (By default [cssnano](https://github.com/cssnano/cssnano)).
Return `true` to keep the warning, or a falsy value (`false`/`null`/`undefined`) to suppress it.
> [!WARNING]
>
> The `source` argument will contain `undefined` if you don't use source maps.
> The `source` parameter will be `undefined` unless source maps are enabled.

@@ -483,3 +494,3 @@ **webpack.config.js**

{
test: /.s?css$/,
test: /\.s?css$/,
use: [

@@ -502,3 +513,3 @@ MiniCssExtractPlugin.loader,

Remove all comments (including comments starting with `/*!`).
Remove all comments, including those starting with `/*!`.

@@ -591,4 +602,3 @@ ```js

module.exports = {
// Uncomment if you need source maps
// devtool: "source-map",
// devtool: "source-map", // Uncomment for source maps
optimization: {

@@ -613,4 +623,3 @@ minimize: true,

module.exports = {
// Uncomment if you need source maps
// devtool: "source-map",
// devtool: "source-map", // Uncomment for source maps
optimization: {

@@ -631,6 +640,8 @@ minimize: true,

Please take a moment to read our contributing guidelines if you haven't yet done so.
We welcome all contributions!
[CONTRIBUTING](./.github/CONTRIBUTING.md)
If you're new here, please take a moment to review our contributing guidelines.
[CONTRIBUTING](https://github.com/webpack/css-minimizer-webpack-plugin?tab=contributing-ov-file#contributing)
## License

@@ -644,6 +655,6 @@

[node-url]: https://nodejs.org
[tests]: https://github.com/webpack-contrib/css-minimizer-webpack-plugin/workflows/css-minimizer-webpack-plugin/badge.svg
[tests-url]: https://github.com/webpack-contrib/css-minimizer-webpack-plugin/actions
[cover]: https://codecov.io/gh/webpack-contrib/css-minimizer-webpack-plugin/branch/master/graph/badge.svg
[cover-url]: https://codecov.io/gh/webpack-contrib/css-minimizer-webpack-plugin
[tests]: https://github.com/webpack/css-minimizer-webpack-plugin/workflows/css-minimizer-webpack-plugin/badge.svg
[tests-url]: https://github.com/webpack/css-minimizer-webpack-plugin/actions
[cover]: https://codecov.io/gh/webpack/css-minimizer-webpack-plugin/branch/main/graph/badge.svg
[cover-url]: https://codecov.io/gh/webpack/css-minimizer-webpack-plugin
[discussion]: https://img.shields.io/github/discussions/webpack/webpack

@@ -650,0 +661,0 @@ [discussion-url]: https://github.com/webpack/webpack/discussions

@@ -8,4 +8,4 @@ export = CssMinimizerPlugin;

* @private
* @param {any} input
* @returns {boolean}
* @param {unknown} input Input to check
* @returns {boolean} Whether input is a source map
*/

@@ -15,8 +15,8 @@ private static isSourceMap;

* @private
* @param {Warning | WarningObject | string} warning
* @param {string} file
* @param {WarningsFilter} [warningsFilter]
* @param {TraceMap} [sourceMap]
* @param {Compilation["requestShortener"]} [requestShortener]
* @returns {Error & { hideStack?: boolean, file?: string } | undefined}
* @param {Warning | WarningObject | string} warning Warning
* @param {string} file File name
* @param {WarningsFilter=} warningsFilter Warnings filter
* @param {TraceMap=} sourceMap Source map
* @param {Compilation["requestShortener"]=} requestShortener Request shortener
* @returns {Error & { hideStack?: boolean, file?: string } | undefined} Built warning
*/

@@ -26,7 +26,7 @@ private static buildWarning;

* @private
* @param {Error | ErrorObject | string} error
* @param {string} file
* @param {TraceMap} [sourceMap]
* @param {Compilation["requestShortener"]} [requestShortener]
* @returns {Error}
* @param {Error | ErrorObject | string} error Error
* @param {string} file File name
* @param {TraceMap=} sourceMap Source map
* @param {Compilation["requestShortener"]=} requestShortener Request shortener
* @returns {Error} Built error
*/

@@ -36,4 +36,4 @@ private static buildError;

* @private
* @param {Parallel} parallel
* @returns {number}
* @param {Parallel} parallel Parallel option
* @returns {number} Available number of cores
*/

@@ -44,8 +44,8 @@ private static getAvailableNumberOfCores;

* @template T
* @param {BasicMinimizerImplementation<T> & MinimizeFunctionHelpers} implementation
* @returns {boolean}
* @param {BasicMinimizerImplementation<T> & MinimizeFunctionHelpers} implementation Implementation
* @returns {boolean} Whether worker threads are supported
*/
private static isSupportsWorkerThreads;
/**
* @param {BasePluginOptions & DefinedDefaultMinimizerAndOptions<T>} [options]
* @param {BasePluginOptions & DefinedDefaultMinimizerAndOptions<T>=} options Plugin options
*/

@@ -64,12 +64,12 @@ constructor(

* @private
* @param {Compiler} compiler
* @param {Compilation} compilation
* @param {Record<string, import("webpack").sources.Source>} assets
* @param {{availableNumberOfCores: number}} optimizeOptions
* @returns {Promise<void>}
* @param {Compiler} compiler Compiler
* @param {Compilation} compilation Compilation
* @param {Record<string, import("webpack").sources.Source>} assets Assets
* @param {{availableNumberOfCores: number}} optimizeOptions Optimize options
* @returns {Promise<void>} Promise
*/
private optimize;
/**
* @param {Compiler} compiler
* @returns {void}
* @param {Compiler} compiler Compiler
* @returns {void} Void
*/

@@ -137,3 +137,7 @@ apply(compiler: Compiler): void;

type JestWorker = import("jest-worker").Worker;
type RawSourceMap = import("@jridgewell/trace-mapping").EncodedSourceMap;
type RawSourceMap = import("@jridgewell/trace-mapping").EncodedSourceMap & {
sources: string[];
sourcesContent?: string[];
file: string;
};
type Asset = import("webpack").Asset;

@@ -145,6 +149,3 @@ type ProcessOptions = import("postcss").ProcessOptions;

type TraceMap = import("@jridgewell/trace-mapping").TraceMap;
type CssNanoOptions = {
configFile?: string | undefined;
preset?: [string, object] | string | undefined;
};
type CssNanoOptions = Record<string, unknown>;
type Warning =

@@ -158,19 +159,58 @@ | (Error & {

type WarningObject = {
/**
* Warning message
*/
message: string;
/**
* Plugin name
*/
plugin?: string | undefined;
/**
* Warning text
*/
text?: string | undefined;
/**
* Line number
*/
line?: number | undefined;
/**
* Column number
*/
column?: number | undefined;
};
type ErrorObject = {
/**
* Error message
*/
message: string;
/**
* Line number
*/
line?: number | undefined;
/**
* Column number
*/
column?: number | undefined;
/**
* Error stack trace
*/
stack?: string | undefined;
};
type MinimizedResult = {
/**
* Minimized code
*/
code: string;
map?: import("@jridgewell/trace-mapping").EncodedSourceMap | undefined;
errors?: (string | Error | ErrorObject)[] | undefined;
warnings?: (Warning | WarningObject)[] | undefined;
/**
* Source map
*/
map?: RawSourceMap | undefined;
/**
* Errors
*/
errors?: Array<Error | ErrorObject | string> | undefined;
/**
* Warnings
*/
warnings?: Array<Warning | WarningObject | string> | undefined;
};

@@ -181,3 +221,3 @@ type Input = {

type CustomOptions = {
[key: string]: any;
[key: string]: unknown;
};

@@ -194,2 +234,5 @@ type InferDefaultType<T> = T extends infer U ? U : CustomOptions;

type MinimizeFunctionHelpers = {
/**
* Check if worker threads are supported
*/
supportsWorkerThreads?: (() => boolean | undefined) | undefined;

@@ -204,5 +247,17 @@ };

type InternalOptions<T> = {
/**
* Name
*/
name: string;
/**
* Input
*/
input: string;
/**
* Input source map
*/
inputSourceMap: RawSourceMap | undefined;
/**
* Minimizer
*/
minimizer: {

@@ -214,2 +269,5 @@ implementation: MinimizerImplementation<T>;

type InternalResult = {
/**
* - Outputs
*/
outputs: Array<{

@@ -219,3 +277,9 @@ code: string;

}>;
/**
* - Warnings
*/
warnings: Array<Warning | WarningObject | string>;
/**
* - Errors
*/
errors: Array<Error | ErrorObject | string>;

@@ -232,11 +296,26 @@ };

type BasePluginOptions = {
/**
* Test rule
*/
test?: Rule | undefined;
/**
* Include rule
*/
include?: Rule | undefined;
/**
* Exclude rule
*/
exclude?: Rule | undefined;
/**
* Warnings filter
*/
warningsFilter?: WarningsFilter | undefined;
parallel?: Parallel;
/**
* Parallel option
*/
parallel?: Parallel | undefined;
};
type MinimizerWorker<T> = JestWorker & {
transform: (options: string) => InternalResult;
minify: (options: InternalOptions<T>) => InternalResult;
transform: (options: string) => Promise<InternalResult>;
minify: (options: InternalOptions<T>) => Promise<InternalResult>;
};

@@ -243,0 +322,0 @@ type ProcessOptionsExtender =

@@ -7,4 +7,4 @@ export type MinimizedResult = import("./index.js").MinimizedResult;

* @template T
* @param {import("./index.js").InternalOptions<T>} options
* @returns {Promise<InternalResult>}
* @param {import("./index.js").InternalOptions<T>} options Options
* @returns {Promise<InternalResult>} Promise with internal result
*/

@@ -15,5 +15,5 @@ export function minify<T>(

/**
* @param {string} options
* @returns {Promise<InternalResult>}
* @param {string} options Options string
* @returns {Promise<InternalResult>} Promise with internal result
*/
export function transform(options: string): Promise<InternalResult>;
export type Task<T> = () => Promise<T>;
export type Input = import("./index.js").Input;
export type RawSourceMap = import("@jridgewell/trace-mapping").EncodedSourceMap;
export type RawSourceMap = import("./index.js").RawSourceMap;
export type MinimizedResult = import("./index.js").MinimizedResult;

@@ -9,29 +9,25 @@ export type CustomOptions = import("./index.js").CustomOptions;

/**
* @template T
* @typedef {() => Promise<T>} Task
* @param {Input} input Input
* @param {RawSourceMap=} sourceMap Source map
* @param {CustomOptions=} minimizerOptions Minimizer options
* @returns {Promise<MinimizedResult>} Promise with minimized result
*/
export function cleanCssMinify(
input: Input,
sourceMap?: RawSourceMap | undefined,
minimizerOptions?: CustomOptions | undefined,
): Promise<MinimizedResult>;
export namespace cleanCssMinify {
function supportsWorkerThreads(): boolean;
}
/**
* Run tasks with limited concurrency.
* @template T
* @param {number} limit - Limit of tasks that run at once.
* @param {Task<T>[]} tasks - List of tasks to run.
* @returns {Promise<T[]>} A promise that fulfills to an array of the results
* @param {Input} input Input
* @param {RawSourceMap=} sourceMap Source map
* @param {CustomOptions=} minimizerOptions Minimizer options
* @returns {Promise<MinimizedResult>} Promise with minimized result
*/
export function throttleAll<T>(limit: number, tasks: Task<T>[]): Promise<T[]>;
/**
* @template T
* @param fn {(function(): any) | undefined}
* @returns {function(): T}
*/
export function memoize<T>(fn: (() => any) | undefined): () => T;
/**
* @param {Input} input
* @param {RawSourceMap | undefined} sourceMap
* @param {CustomOptions} [minimizerOptions]
* @return {Promise<MinimizedResult>}
*/
export function cssnanoMinify(
input: Input,
sourceMap: RawSourceMap | undefined,
minimizerOptions?: import("./index.js").CustomOptions | undefined,
sourceMap?: RawSourceMap | undefined,
minimizerOptions?: CustomOptions | undefined,
): Promise<MinimizedResult>;

@@ -42,11 +38,11 @@ export namespace cssnanoMinify {

/**
* @param {Input} input
* @param {RawSourceMap | undefined} sourceMap
* @param {CustomOptions} [minimizerOptions]
* @return {Promise<MinimizedResult>}
* @param {Input} input Input
* @param {RawSourceMap=} sourceMap Source map
* @param {CustomOptions=} minimizerOptions Minimizer options
* @returns {Promise<MinimizedResult>} Promise with minimized result
*/
export function cssoMinify(
input: Input,
sourceMap: RawSourceMap | undefined,
minimizerOptions?: import("./index.js").CustomOptions | undefined,
sourceMap?: RawSourceMap | undefined,
minimizerOptions?: CustomOptions | undefined,
): Promise<MinimizedResult>;

@@ -57,39 +53,45 @@ export namespace cssoMinify {

/**
* @param {Input} input
* @param {RawSourceMap | undefined} sourceMap
* @param {CustomOptions} [minimizerOptions]
* @return {Promise<MinimizedResult>}
* @param {Input} input Input
* @param {RawSourceMap=} sourceMap Source map
* @param {CustomOptions=} minimizerOptions Minimizer options
* @returns {Promise<MinimizedResult>} Promise with minimized result
*/
export function cleanCssMinify(
export function esbuildMinify(
input: Input,
sourceMap: RawSourceMap | undefined,
minimizerOptions?: import("./index.js").CustomOptions | undefined,
sourceMap?: RawSourceMap | undefined,
minimizerOptions?: CustomOptions | undefined,
): Promise<MinimizedResult>;
export namespace cleanCssMinify {
export namespace esbuildMinify {
function supportsWorkerThreads(): boolean;
}
/**
* @param {Input} input
* @param {RawSourceMap | undefined} sourceMap
* @param {CustomOptions} [minimizerOptions]
* @return {Promise<MinimizedResult>}
* @param {Input} input Input
* @param {RawSourceMap=} sourceMap Source map
* @param {CustomOptions=} minimizerOptions Minimizer options
* @returns {Promise<MinimizedResult>} Promise with minimized result
*/
export function esbuildMinify(
export function lightningCssMinify(
input: Input,
sourceMap: RawSourceMap | undefined,
minimizerOptions?: import("./index.js").CustomOptions | undefined,
sourceMap?: RawSourceMap | undefined,
minimizerOptions?: CustomOptions | undefined,
): Promise<MinimizedResult>;
export namespace esbuildMinify {
export namespace lightningCssMinify {
function supportsWorkerThreads(): boolean;
}
/**
* @param {Input} input
* @param {RawSourceMap | undefined} sourceMap
* @param {CustomOptions} [minimizerOptions]
* @return {Promise<MinimizedResult>}
* @template T
* @param {(() => unknown) | undefined} fn Function to memoize
* @returns {() => T} Memoized function
*/
export function memoize<T>(fn: (() => unknown) | undefined): () => T;
/**
* @param {Input} input Input
* @param {RawSourceMap=} sourceMap Source map
* @param {CustomOptions=} minimizerOptions Minimizer options
* @returns {Promise<MinimizedResult>} Promise with minimized result
*/
export function parcelCssMinify(
input: Input,
sourceMap: RawSourceMap | undefined,
minimizerOptions?: import("./index.js").CustomOptions | undefined,
sourceMap?: RawSourceMap | undefined,
minimizerOptions?: CustomOptions | undefined,
): Promise<MinimizedResult>;

@@ -100,28 +102,26 @@ export namespace parcelCssMinify {

/**
* @param {Input} input
* @param {RawSourceMap | undefined} sourceMap
* @param {CustomOptions} [minimizerOptions]
* @return {Promise<MinimizedResult>}
* @param {Input} input Input
* @param {RawSourceMap=} sourceMap Source map
* @param {CustomOptions=} minimizerOptions Minimizer options
* @returns {Promise<MinimizedResult>} Promise with minimized result
*/
export function lightningCssMinify(
export function swcMinify(
input: Input,
sourceMap: RawSourceMap | undefined,
minimizerOptions?: import("./index.js").CustomOptions | undefined,
sourceMap?: RawSourceMap | undefined,
minimizerOptions?: CustomOptions | undefined,
): Promise<MinimizedResult>;
export namespace lightningCssMinify {
export namespace swcMinify {
function supportsWorkerThreads(): boolean;
}
/**
* @param {Input} input
* @param {RawSourceMap | undefined} sourceMap
* @param {CustomOptions} [minimizerOptions]
* @return {Promise<MinimizedResult>}
* @template T
* @typedef {() => Promise<T>} Task
*/
export function swcMinify(
input: Input,
sourceMap: RawSourceMap | undefined,
minimizerOptions?: import("./index.js").CustomOptions | undefined,
): Promise<MinimizedResult>;
export namespace swcMinify {
function supportsWorkerThreads(): boolean;
}
/**
* Run tasks with limited concurrency.
* @template T
* @param {number} limit Limit of tasks that run at once.
* @param {Task<T>[]} tasks List of tasks to run.
* @returns {Promise<T[]>} A promise that fulfills to an array of the results
*/
export function throttleAll<T>(limit: number, tasks: Task<T>[]): Promise<T[]>;