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

@pi-r/clean-css
 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

  1. Typings (optional)

  2. none

  3. none

  4. none

  5. context = require(“clean-css”), value = source code, options = TransformSeries instance

  6. When calling process (cwd) uses a different major package version (optional)

  7. Main sourceMap from previous consumer

  8. Applies options.external AND options.outputConfig to options.baseConfig (optional)

  9. none

  10. Delete current sourceMap as requested using sourceMap.reset

  11. none

  12. none

  13. Check if there is an existing sourceMap and pass it through

  14. none

  15. none

  16. Call package transform method with baseConfig and value

  17. Check if method succeeded

  18. Check if a sourceMap was generated

  19. Pass sourceMap output values to sourceMap.nextMap chain method

  20. none

  21. 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.