tezvyn:

Build a custom PostCSS plugin (px to rem)

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

PostCSS as an AST transformer.

OUTLINE

export a plugin returning visitor hooks, walk Declaration nodes, parse and rewrite px values to rem against a base size.

RED FLAG

treating CSS as a regex string, not a parsed tree.

WHAT THIS TESTS Whether you understand PostCSS as a tool that parses CSS into a structured Abstract Syntax Tree and lets you transform nodes, rather than doing brittle text manipulation.

A GOOD ANSWER COVERS A PostCSS plugin is a function that returns an object. That object has a postcssPlugin name and visitor methods keyed by node type, such as Declaration, Rule, or AtRule. PostCSS parses the input into an AST whose nodes include rules, declarations with prop and value, comments, and at-rules. Your plugin walks the tree and PostCSS calls your Declaration visitor for each declaration. Inside it you check the prop against an allowed list, parse the value to find numeric px tokens, divide each by a configurable base font size, and rewrite the value with rem units. Accept options so the base size and target properties are configurable. Keep it idempotent so re-running does not double-convert, and skip values inside url() or already in rem.

COMMON WRONG ANSWERS Doing a global regex replace on the raw stylesheet string corrupts comments, data URIs, and unrelated numbers, and ignores the parser PostCSS gives you for free. Mutating nodes without checking the property converts things like z-index. Hardcoding the base size instead of exposing an option.

LIKELY FOLLOW-UPS How do you avoid converting border widths you want in px? Use an exclusion list or a comment directive. How do you test it? Feed input CSS through the processor and assert the output string. Why visitors over walkDecls? Visitors integrate with PostCSS performance and ordering.

ONE CONCRETE EXAMPLE Given font-size: 16px with a base of 16, the Declaration visitor sees prop font-size, parses 16px, computes 1, and rewrites the declaration value to 1rem. A declaration like background: url(a.png) is untouched because its value has no bare px number on a targeted property. Border-width stays in px if excluded by configuration.

Read the original → github.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.