@adobe/css-tools provides a modern CSS parser and stringifier with comprehensive TypeScript support. It can parse CSS into an Abstract Syntax Tree (AST) and convert the AST back to CSS with various formatting options.
npm install @adobe/css-toolsParses CSS code and returns an Abstract Syntax Tree (AST).
code(string) - The CSS code to parseoptions(object, optional) - Parsing optionssilent(boolean) - Collect recoverable parse errors inast.stylesheet.parsingErrorsinstead of throwing. Some recovery failures can still throw; see known V5 limitations.source(string) - File path for better error reportingstripCommentsInValues(boolean, default:true) - Apply V4-style declaration-value normalization, removing/* ... */text even inside quoted strings. Set tofalseto preserve leading, embedded, and trailing value comments. Standalone comment AST nodes are unaffected.
CssStylesheetAST- The parsed CSS as an AST
import { parse } from '@adobe/css-tools';
const css = `
.example {
color: red;
font-size: 16px;
}
`;
const ast = parse(css);
console.log(ast.stylesheet.rules);V4 historically treats comment-like text inside quoted values as a comment. V5 preserves this behavior by default, with an explicit opt-out:
const css = 'a { content: "/* literal text */"; }';
parse(css).stylesheet.rules[0].declarations[0].value;
// => '""'
parse(css, { stripCommentsInValues: false })
.stylesheet.rules[0].declarations[0].value;
// => '"/* literal text */"'The option is part of the exported ParseOptions TypeScript interface.
Input source maps are not loaded. sourceMappingURL comments are parsed like
ordinary CSS comments; positions and parse errors refer to the provided CSS.
Two upstream resource limitations are accepted
and will not be fixed in css-tools. Core PostCSS takes superlinear time on
at-rule headers with many leading comments. Separately, postcss-safe-parser
can exhaust the stack or memory on long sequences without declaration
semicolons. Both occur before the compatibility layer receives an AST and affect
strict and silent parsing. Exact V4 behavior is not guaranteed outside the tested
compatibility corpus.
Converts a CSS AST back to CSS string with configurable formatting.
ast(CssStylesheetAST) - The CSS AST to stringifyoptions(CompilerOptions, optional) - Stringification optionsindent(string) - Indentation string (default:' ')compress(boolean) - Whether to compress/minify the output (default:false)
string- The formatted CSS string
import { parse, stringify } from '@adobe/css-tools';
const css = '.example { color: red; }';
const ast = parse(css);
// Pretty print
const formatted = stringify(ast, { indent: ' ' });
console.log(formatted);
// Output:
// .example {
// color: red;
// }
// Compressed
const minified = stringify(ast, { compress: true });
console.log(minified);
// Output: .example{color:red}The root AST node representing a complete CSS stylesheet.
type CssStylesheetAST = {
type: CssTypes.stylesheet;
stylesheet: {
source?: string;
rules: CssRuleAST[];
parsingErrors?: CssParseError[];
};
};Represents a CSS rule (selector + declarations).
type CssRuleAST = {
type: CssTypes.rule;
selectors: string[];
declarations: CssDeclarationAST[];
position?: CssPosition;
parent?: CssStylesheetAST;
};Represents a CSS property declaration.
type CssDeclarationAST = {
type: CssTypes.declaration;
property: string;
value: string;
position?: CssPosition;
parent?: CssRuleAST;
};Represents a CSS @media rule.
type CssMediaAST = {
type: CssTypes.media;
media: string;
rules: CssRuleAST[];
position?: CssPosition;
parent?: CssStylesheetAST;
};Represents a CSS @keyframes rule.
type CssKeyframesAST = {
type: CssTypes.keyframes;
name: string;
keyframes: CssKeyframeAST[];
position?: CssPosition;
parent?: CssStylesheetAST;
};Represents source position information.
type CssPosition = {
source?: string;
start: {
line: number;
column: number;
};
end: {
line: number;
column: number;
};
};Represents a parsing error.
type CssParseError = {
message: string;
reason: string;
filename?: string;
line: number;
column: number;
source?: string;
};Options for the stringifier.
type CompilerOptions = {
indent?: string; // Default: ' '
compress?: boolean; // Default: false
};For recoverable syntax errors, use the silent option to collect errors
instead of throwing:
import { parse } from '@adobe/css-tools';
const malformedCss = `
body { color: red; }
{ color: blue; } /* Missing selector */
.valid { background: green; }
`;
const result = parse(malformedCss, { silent: true });
if (result.stylesheet.parsingErrors) {
result.stylesheet.parsingErrors.forEach(error => {
console.log(`Error at line ${error.line}: ${error.message}`);
});
}
// Valid rules are still parsed
console.log('Valid rules:', result.stylesheet.rules.length);Silent mode does not guarantee that parsing returns an AST or finishes within
a bounded time. Core PostCSS's leading-comment token handling and
postcss-safe-parser's missing-semicolon recovery are
known V5 limitations that will not be fixed
in css-tools. Bound untrusted input size and use a worker or process with an
externally enforceable timeout; an in-process timer cannot interrupt synchronous
parsing.
Enable source tracking for better error reporting:
import { parse } from '@adobe/css-tools';
const css = 'body { color: red; }';
const ast = parse(css, { source: 'styles.css' });
const rule = ast.stylesheet.rules[0];
console.log(rule.position?.source); // "styles.css"
console.log(rule.position?.start); // { line: 1, column: 1 }
console.log(rule.position?.end); // { line: 1, column: 20 }import { parse, stringify } from '@adobe/css-tools';
const css = `
@media (max-width: 768px) {
.container {
padding: 10px;
}
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
`;
const ast = parse(css);
// Access media rules
const mediaRule = ast.stylesheet.rules.find(rule => rule.type === 'media');
console.log(mediaRule.media); // "(max-width: 768px)"
// Access keyframes
const keyframesRule = ast.stylesheet.rules.find(rule => rule.type === 'keyframes');
console.log(keyframesRule.name); // "fadeIn"import { parse, stringify } from '@adobe/css-tools';
const css = '.example{color:red;font-size:16px}';
const ast = parse(css);
// Custom indentation
const formatted = stringify(ast, { indent: ' ' });
console.log(formatted);
// Output:
// .example {
// color: red;
// font-size: 16px;
// }
// Compressed with no spaces
const compressed = stringify(ast, { compress: true });
console.log(compressed);
// Output: .example{color:red;font-size:16px}The library provides comprehensive TypeScript support with full type definitions for all AST nodes and functions:
import { parse, stringify, type CssStylesheetAST } from '@adobe/css-tools';
const css: string = '.example { color: red; }';
const ast: CssStylesheetAST = parse(css);
const output: string = stringify(ast);- Parsing performance depends on the input; upstream safe-parser recovery can exhaust the stack or memory on long sequences without semicolons
- AST nodes are lightweight and memory-efficient
- Stringification is fast and supports streaming for large outputs
- Consider using
compress: truefor production builds to reduce file size
The library works in all modern browsers and Node.js environments. For older environments, you may need to use a bundler with appropriate polyfills.