skip to content

When writing a PostCSS 8 plugin that rewrites a legacy --gutter-units declaration, which listeners do you use, and how do you avoid an endless re-visit loop?

level: seniorimportance: nice to knowfreq 5%

answer

  1. an object with a name
  2. creator flagged with postcss = true
  3. a Declaration listener keyed by prop
  4. prepare() for per-file state
  5. changed nodes are visited again

basics

~20 s

Export a creator, flagged postcss = true, returning postcssPlugin and listeners. Use a Declaration listener keyed to --gutter-units, prepare(result) for per-file state, and make each change stop matching, since PostCSS 8 re-visits every changed node.

solid answer

~50 s

In PostCSS 8 a plugin is a creator function, flagged with `plugin.postcss = true`, that returns an object with a `postcssPlugin` name and listeners. Enter listeners (`Once`, `Root`, `AtRule`, `Rule`) run before a node's children, and exit listeners (`OnceExit`, `RuleExit` ...) after them. `Declaration` takes either a function or an object keyed by property, so `'--gutter-units'` fires only for that declaration. Per-file state belongs in `prepare(result)`, which returns fresh listeners for each processing run and gives access to `result` for warnings. The trap is re-visiting: PostCSS walks again over every node a plugin changed or added, and over its parent; only `Once` and `OnceExit` are not called again. Renaming the property to `--gutter` makes the node stop matching, so the walk ends. A listener that appends children without checking for earlier work loops forever. The old `postcss.plugin()` wrapper was deprecated in PostCSS 8.0.

code

javascript · 29 lines
javascript
// postcss/gutter-units.js: --gutter-units: 3  ->  --gutter: 24px
const plugin = (opts = {}) => {
  const step = opts.step ?? 8 // px per legacy unit
  return {
    postcssPlugin: 'gutter-units',
    prepare(result) {
      let rewritten = 0 // fresh for every file
      return {
        Declaration: {
          '--gutter-units': (decl) => {
            const units = decl.value.trim()
            if (!/^\d+(\.\d+)?$/.test(units)) {
              decl.warn(result, `--gutter-units needs a number, got "${units}"`)
              return
            }
            decl.prop = '--gutter' // stops matching this listener
            decl.value = `${Number(units) * step}px`
            rewritten += 1
          }
        },
        OnceExit() {
          if (rewritten > 0) result.warn(`${rewritten} legacy --gutter-units rewritten`)
        }
      }
    }
  }
}
plugin.postcss = true
module.exports = plugin

go deeper

for a junior

Recall that a PostCSS plugin is a function returning an object with a postcssPlugin name and listeners named after node types such as Declaration and Rule.

for a middle

Explain enter and exit listeners, the keyed Declaration form, and why the creator carries postcss = true instead of using the old postcss.plugin wrapper.

for a senior

Show the re-visit rule in action: write a change that stops matching, guard listeners that add children, keep state in prepare(), warn with source positions and copy source on new nodes.

for a principal

Weigh an in-house plugin as a codebase migration tool: a temporary rewrite with warnings that track remaining legacy usage, against fixing the source once and deleting the plugin.

## The shape of a PostCSS 8 plugin A plugin is a **creator function** that returns a plain object: - `postcssPlugin`: the plugin's name, used in warnings and errors. - One or more **listeners**: methods named after node types, called as PostCSS walks the tree. - Optionally `prepare(result)`, which returns the listeners per processing run. The creator itself is flagged with `plugin.postcss = true`, so a config can list it either called (`gutterUnits({ step: 8 })`) or uncalled. In TypeScript, type it as `PluginCreator<Options>` so the flag type-checks. The PostCSS 7 wrapper `postcss.plugin('name', fn)` was **deprecated in PostCSS 8.0**, and calling it now prints a deprecation warning with a migration guide. A plugin today is the creator described here. ## The listeners | Listener | Fires | Notes | |---|---|---| | `Once` | once per file, before the walk | the whole `Root`; not repeated | | `Root`, `AtRule`, `Rule` | entering a node, before its children | repeated when the node changes | | `Declaration`, `Comment` | on each matching node | `Declaration` and `AtRule` accept an object keyed by property or at-rule name, plus `'*'` | | `RootExit`, `AtRuleExit`, `RuleExit`, `DeclarationExit` | after a node's children are done | repeated on change | | `OnceExit` | once per file, after the walk | not repeated; Autoprefixer does its work here | Listeners receive the node and a **helpers** object holding node constructors (`Rule`, `Declaration` ...) and `result`. Use `decl.warn(result, message)` to report a problem with the node's source position. Use `throw decl.error(message)` for a real syntax error. When you create a node, copy `source` from the node it replaces so source maps stay correct. ## Per-file state belongs in `prepare()` The creator runs once, when the processor is built. A single processor may then handle many files and many watch-mode rebuilds. A counter declared in the creator's scope would therefore be shared, and would accumulate across every file. `prepare(result)` runs **per processing run**, so state declared inside it is fresh for each file, and it can read `result.opts.from`. Autoprefixer itself is written this way: `prepare` loads the Browserslist targets for the file being processed, and `OnceExit` adds and removes prefixes. ## The re-visit rule, and the loop it can cause From the PostCSS docs: plugins **re-visit every node they changed or added**, and if a child changes, the **parent is re-visited** as well. Only `Once` and `OnceExit` are not called again. Two consequences follow: 1. **A change that still matches its own listener runs again.** The documented example sets `decl.value = 'red'` in a `Declaration` listener: the `Rule` and `Declaration` listeners both fire a second time. 2. **Adding children without a guard loops forever.** A `Rule` listener that appends a fallback declaration changes the rule, the rule is visited again, and the listener appends again. Guard it by checking for earlier work, for example `rule.some(d => d.prop === 'x')`, or by marking processed nodes with a `Symbol`. The `--gutter-units` plugin in the example avoids both. It renames the property to `--gutter`, so on the re-visit its keyed listener no longer matches. When the value is not a number, it warns and leaves the node unchanged, so there is nothing to re-visit. ## Steps to build it 1. Start from the official plugin boilerplate or the template in the docs. 2. Find nodes with the narrowest listener (here a keyed `Declaration`), and use a cheap `String#includes()` test before any heavy value parsing. 3. Change nodes so the change no longer matches its own listener, or guard with a check. 4. Warn rather than throw for content an author can fix later. 5. Write tests first. The boilerplate ships a test template, and an AST explorer shows how sample CSS parses. ## Where it sits in the pipeline The rewrite is non-standard, so it runs after postcss-import and before postcss-preset-env. The renamed `--gutter` declaration then flows through lowering and minification like any other custom property. ## Testing the re-visit behaviour A good test suite for a plugin like this covers three cases: - **The happy path**: `--gutter-units: 3` becomes `--gutter: 24px`, and a second run over the output changes nothing, which shows the rewrite is idempotent. - **The bad input**: a non-numeric value produces exactly one warning with the right line, and the declaration is left as written. - **The neighbours**: other custom properties and ordinary declarations in the same rule pass through untouched. The idempotence check is a cheap early warning for the re-visit loop. If a second pass over the output changes it again, the rewrite still matches its own result, which is the same condition that makes PostCSS re-visit and loop.

  • Why keep the counter in `prepare(result)` rather than in the creator's scope?
    The creator runs once when the processor is built, and that processor may handle many files and rebuilds, so creator-level state is shared and keeps growing. `prepare(result)` runs for each processing run and returns fresh listeners with fresh state, and gives access to `result` for warnings and options such as `from`.
  • What replaced `postcss.plugin()`, and how do you recognise code that still uses it?
    PostCSS 8.0 deprecated the `postcss.plugin('name', fn)` wrapper. A current plugin is a creator returning `{ postcssPlugin, ...listeners }`, with `creator.postcss = true` set on the function. Calling the old wrapper still works but prints a deprecation warning with a migration guide, which is the usual sign of a plugin written for PostCSS 7.
  • When your plugin creates a new node, what must you copy, and why?
    Copy `source` from the node it replaces or derives from, for example `new Rule({ selector: 'a', source: node.source })`. PostCSS builds source maps and warning positions from each node's `source`, so a node without one points nowhere in the original file.

  • A PostCSS 8 plugin is registered with postcss.plugin('name', fn).
  • Each listener runs once per node, so changing a node never triggers it again.
  • State in the plugin creator's closure starts fresh for every file.
  • Once and OnceExit fire again after a node changes, like the other listeners.
  • New nodes need no source; source maps are rebuilt from the output text.

Assumes PostCSS 8 (8.5.29): the visitor listeners and prepare() arrived with 8.0, which also deprecated the postcss.plugin() wrapper.