{"id":13022,"library":"css","title":"CSS Parser/Stringifier","description":"The `css` package is a fundamental JavaScript library designed for robust parsing and stringifying of Cascading Style Sheets (CSS). It serves as a core component for various CSS processing tools, including preprocessors, postprocessors, and linting utilities. At its current stable version, 3.0.0, it offers `css.parse()` to convert raw CSS strings into a detailed Abstract Syntax Tree (AST) object, and `css.stringify()` to transform such an AST back into a minified or formatted CSS string. The library provides comprehensive options for error handling, including a 'silent' mode for collecting parsing errors without throwing, and extensive support for source map generation to maintain traceability between original and processed CSS. Its primary differentiator lies in its adherence to the reworkcss AST specification, offering a consistent and manipulable representation of CSS for complex transformations. While the provided documentation highlights CommonJS usage, modern projects might explore ESM compatibility, though it's not explicitly documented in the given excerpt. The project generally follows semantic versioning without a fixed release cadence.","status":"active","version":"3.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/reworkcss/css","tags":["javascript","css","parser","stringifier","stylesheet"],"install":[{"cmd":"npm install css","lang":"bash","label":"npm"},{"cmd":"yarn add css","lang":"bash","label":"yarn"},{"cmd":"pnpm add css","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary 'css' object is typically imported via CommonJS 'require'. It contains the 'parse' and 'stringify' methods. Direct ES Module imports are not explicitly documented as supported in v3.x, and may require specific build configurations.","wrong":"import css from 'css';","symbol":"css","correct":"const css = require('css');"},{"note":"The 'parse' function is a method on the main 'css' object. Direct named imports are not the documented pattern for v3.x, which uses a CommonJS module export for the main object.","wrong":"import { parse } from 'css';","symbol":"css.parse","correct":"const css = require('css');\nconst ast = css.parse('body { color: red; }');"},{"note":"The 'stringify' function is a method on the main 'css' object. Direct named imports are not the documented pattern for v3.x, which uses a CommonJS module export for the main object.","wrong":"import { stringify } from 'css';","symbol":"css.stringify","correct":"const css = require('css');\nconst cssString = css.stringify(ast);"}],"quickstart":{"code":"const css = require('css');\n\n// Example CSS string\nconst inputCss = `\n  /* This is a comment */\n  body {\n    font-family: Arial, sans-serif;\n    font-size: 16px; /* Default size */\n    color: #333;\n  }\n  @media (max-width: 600px) {\n    body {\n      font-size: 14px;\n    }\n  }\n`;\n\n// Parse the CSS string into an AST\nconst ast = css.parse(inputCss, {\n  source: 'example.css', // Recommended for better error messages and sourcemaps\n  silent: false          // Set to true to collect errors instead of throwing\n});\n\nconsole.log('Parsed AST (partial):', JSON.stringify(ast.stylesheet.rules[0], null, 2));\n\n// Stringify the AST back into CSS\nconst outputCss = css.stringify(ast, {\n  indent: '  ', // Use two spaces for indentation\n  compress: false // Do not compress, maintain readability\n});\nconsole.log('\\nStringified CSS:\\n', outputCss);\n\n// Stringify with compression\nconst compressedCss = css.stringify(ast, { compress: true });\nconsole.log('\\nCompressed CSS:\\n', compressedCss);\n\n// Example with sourcemap\nconst resultWithMap = css.stringify(ast, { sourcemap: true, source: 'example.css' });\nconsole.log('\\nCSS with sourcemap (first 100 chars):\\n', resultWithMap.code.substring(0, 100) + '...');\n// console.log('Generated Sourcemap:', resultWithMap.map); // uncomment to see the map object","lang":"javascript","description":"Demonstrates parsing CSS into an AST, stringifying it back, and generating compressed output or sourcemaps using the `css.parse` and `css.stringify` functions."},"warnings":[{"fix":"After calling `css.parse` with `silent: true`, always check `ast.stylesheet.parsingErrors` for any `Error` objects and handle them appropriately.","message":"When parsing CSS with the `silent: true` option, errors are not thrown but collected in the `parsingErrors` property of the `stylesheet` node. Developers must explicitly check this property to identify and handle parse failures, as no exceptions will be raised directly.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Pass `source: 'your-filename.css'` as an option to `css.parse` when you intend to generate source maps later with `css.stringify`.","message":"To generate meaningful source maps with `css.stringify`, it is highly recommended to provide the `source` option during the `css.parse` step. Without this option, the generated source maps might contain less useful or incomplete source file information.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Set `inputSourcemaps: false` in `css.stringify` options if you want to explicitly disable reading external source maps and avoid potential file system I/O.","message":"The `inputSourcemaps` option is enabled by default during `css.stringify` and can potentially lead to file system access if the input AST nodes reference external source maps. This might introduce unexpected I/O operations or performance implications in environments where file system access is restricted or undesirable.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"For reliable module loading in Node.js environments, use `const css = require('css');`. For browser or ES Module-only environments, ensure your build setup correctly handles CommonJS modules or transpile them as needed.","message":"The `css` package in version 3.x is primarily distributed and documented as a CommonJS module. Attempting to use ES Module `import` syntax directly might lead to runtime errors or require specific build tool configurations (like Babel or webpack) to transpile CommonJS into an compatible ES Module import, even though some environments might offer interoperability.","severity":"breaking","affected_versions":"3.x"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure the `css` package is correctly installed (`npm install css`) and that `require('css')` executes successfully. Verify no other variable named `css` is clashing with the imported module.","cause":"The `css` module was not correctly loaded or returned an `undefined` or `null` object, preventing access to its methods.","error":"TypeError: Cannot read properties of undefined (reading 'parse')"},{"fix":"Inspect the CSS at the reported line and column number, and correct any syntax errors. Alternatively, use `options: { silent: true }` in `css.parse` to collect errors in `ast.stylesheet.parsingErrors` instead of throwing them immediately.","cause":"The input CSS string provided to `css.parse` contains syntax errors, is incomplete, or malformed according to CSS specifications.","error":"Parse error at <line>:<column>: <reason>"},{"fix":"Verify that the AST structure, especially `node.type` and `node.stylesheet.rules`, is correct and complete. Compare your AST against the output of a known good `css.parse` call or refer to the AST explorer (http://iamdustan.com/reworkcss_ast_explorer/) for validation.","cause":"The Abstract Syntax Tree (AST) object passed to `css.stringify` is invalid, malformed, or does not conform to the expected reworkcss AST structure, often missing critical properties like `type` or `stylesheet.rules`.","error":"TypeError: Cannot read properties of null (reading 'type')"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}