{"id":13019,"library":"css-simple-parser","title":"CSS Simple Parser","description":"CSS Simple Parser is a highly optimized, lightweight parser for (S)CSS strings, weighing in at approximately 1.5kb (min + gzip). It is designed for blazing-fast performance, benchmarking around 100x faster than PostCSS for typical use cases. Currently at version 3.0.2, the library is actively maintained but adheres to a 'too simple' philosophy, focusing on core rule block parsing. Key differentiators include its small footprint and speed, achieved by intentionally limiting its scope. It supports nested (S)CSS rules but does not handle top-level directives like `@charset` or `@import`, nor does it permit curly braces (`{`, `}`) or semicolons (`;`) within string literals. The Abstract Syntax Tree (AST) it generates is intentionally crude, requiring further processing for complex operations. Its release cadence is feature-driven, with new versions addressing enhancements or bug fixes within its defined scope.","status":"active","version":"3.0.2","language":"javascript","source_language":"en","source_url":"https://github.com/fabiospampinato/css-simple-parser","tags":["javascript","css","scss","sass","simple","parser","ast","fast","small","typescript"],"install":[{"cmd":"npm install css-simple-parser","lang":"bash","label":"npm"},{"cmd":"yarn add css-simple-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add css-simple-parser","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library exports a default object named `Parser`, which encapsulates all utility methods like `parse`, `stringify`, and `traverse`.","wrong":"import { Parser } from 'css-simple-parser';","symbol":"Parser","correct":"import Parser from 'css-simple-parser';"},{"note":"The `parse` function is a method of the default `Parser` object, not a direct named export. Access it via `Parser.parse()`.","wrong":"import { parse } from 'css-simple-parser';","symbol":"parse","correct":"import Parser from 'css-simple-parser'; const ast = Parser.parse('.foo {}');"},{"note":"While CommonJS `require` is supported, ES module `import` syntax is generally preferred for modern TypeScript and JavaScript projects, especially when consuming libraries with type definitions.","symbol":"Parser (CommonJS)","correct":"const Parser = require('css-simple-parser');"}],"quickstart":{"code":"import Parser from 'css-simple-parser';\n\nconst cssString = `\n  .container {\n    display: flex;\n    .item {\n      color: red;\n      &:hover {\n        color: blue;\n      }\n    }\n  }\n  @media screen and (max-width: 768px) {\n    .container {\n      flex-direction: column;\n    }\n  }\n`;\n\nconsole.log(\"Parsing CSS string...\");\nconst ast = Parser.parse(cssString);\nconsole.log(\"Generated AST (truncated):\\n\", JSON.stringify(ast, null, 2).substring(0, 300) + '...\\n');\n\nconsole.log(\"Traversing AST and logging selectors:\");\nlet selectorsFound: string[] = [];\nParser.traverse(ast, node => {\n  selectorsFound.push(node.selector);\n});\nconsole.log(selectorsFound.join(', ') + '\\n');\n\nconsole.log(\"Stringifying AST back to CSS (truncated to 150 chars):\");\nconst stringifiedCss = Parser.stringify(ast);\nconsole.log(stringifiedCss.substring(0, 150) + '...\\n');\n\n// Example of modifying the AST and stringifying again\nif (ast.children.length > 0 && ast.children[0].children.length > 0) {\n  const firstNestedItem = ast.children[0].children[0];\n  console.log(`Modifying selector '${firstNestedItem.selector}' to '.new-item-class'\\n`);\n  firstNestedItem.selector = '.new-item-class';\n  const modifiedStringifiedCss = Parser.stringify(ast);\n  console.log(\"Modified CSS (truncated to 150 chars):\\n\", modifiedStringifiedCss.substring(0, 150) + '...');\n}","lang":"typescript","description":"Demonstrates parsing a CSS string with nested rules, traversing the resulting AST to extract selectors, stringifying the AST back into CSS, and then performing a simple AST modification followed by re-stringification."},"warnings":[{"fix":"Ensure your CSS input strictly adheres to the supported syntax (primarily nested rule blocks). For full CSS specification compliance and advanced features, consider using a more comprehensive parser like PostCSS.","message":"This parser is not a full-blown CSS parser and has significant limitations. It only supports rule blocks at the top-level, meaning directives like `@charset`, `@import`, or top-level `@media` rules are not parsed.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Refactor your CSS to avoid these characters within string literals. If your use case absolutely requires them, this parser is not suitable, and an alternative like `css-tree` should be considered.","message":"Curly braces (`{`, `}`) or semicolons (`;`) cannot be used inside string literals within CSS rules. For example, `div[attr=\"{}\"]` or `content: \";\"` will cause parsing errors.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Be prepared to implement custom logic to process the simplified AST nodes to extract specific information or perform advanced manipulations. If you need a highly detailed or standardized AST, explore libraries like `css-tree` or `PostCSS`.","message":"The Abstract Syntax Tree (AST) generated by `css-simple-parser` is deliberately crude and simplified. It provides basic structural information but lacks the rich detail and metadata found in ASTs from more complex parsers.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Modify your CSS to remove `{` or `}` characters from within string values (e.g., `content: \"{}\"` is invalid). If these characters are essential, `css-simple-parser` cannot be used.","cause":"A curly brace (`{` or `}`) was found inside a CSS string literal, which is explicitly disallowed by this parser.","error":"Syntax Error: Unexpected character '{' (or '}') in string"},{"fix":"Modify your CSS to remove `;` characters from within string values (e.g., `div[attr=\";foo\"]` is invalid). If necessary, switch to a more robust parser.","cause":"A semicolon (`;`) was found inside a CSS string literal, which is explicitly disallowed.","error":"Syntax Error: Unexpected character ';' in string"},{"fix":"Ensure your CSS only contains standard rule blocks (e.g., `.selector { ... }`) or nested rules. If you need to parse full CSS specifications, use a different parsing library.","cause":"The input CSS contains a top-level construct other than a rule block, such as `@import`, `@charset`, or `@media`, which are not supported at the root level by `css-simple-parser`.","error":"Parsing failed: Expected rule block at top level"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}