Breakdown
Plugins are simply options
pass-through calls to a context
wrapper method. The only part which might not be intuitive is consuming an existing source map and then saving it for further processing.
Code
1import type { ITransformSeries, RawSourceMap } from "@e-mc/types/lib/document";
2
3import type * as cc from "clean-css";
4
5export default function transform(context: typeof cc, value: string, options: ITransformSeries<cc.OptionsOutput>) {
6 context = options.upgrade(context, __dirname);
7 const sourceMap = options.sourceMap;
8 const baseConfig = options.toBaseConfig(/* true */); // Use "false" for only outputConfig
9 let map: RawSourceMap<string> | undefined;
10 if (baseConfig.sourceMap === false) {
11 sourceMap.reset();
12 }
13 else if (map = sourceMap.map) {
14 baseConfig.sourceMap = true;
15 }
16 const result = new context(baseConfig).minify(value, map);
17 if (result) {
18 if (result.sourceMap) {
19 sourceMap.nextMap("clean-css", result.styles, result.sourceMap.toString());
20 }
21 return result.styles;
22 }
23}
Hint
There are only three lines of relevant TypeScript being used to check for upgrade compatibility. Local file “.cjs” transformers offer the same exact functionality.
Comments
Typings (optional)
none
none
none
context = require(“clean-css”), value = source code, options = TransformSeries instance
When calling process (cwd) uses a different major package version (optional)
Main sourceMap from previous consumer
Applies options.external AND options.outputConfig to options.baseConfig (optional)
none
Delete current sourceMap as requested using
sourceMap.reset
none
none
Check if there is an existing sourceMap and pass it through
none
none
Call package transform method with baseConfig and value
Check if method succeeded
Check if a sourceMap was generated
Pass sourceMap output values to
sourceMap.nextMap
chain methodnone
Return modified transformed source code
Important
Some plugins have a two-step transformation process (e.g. rollup) and use outputConfig separately. It is generally used for inline transformers as their baseConfig.