Registry / serialization / css
library1.0jsnpmunverified

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.

npm install css
INSTALL
IMPORT
SIG · CSS
C
css
serializationjavascriptv1.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

css
const css = require('css');
import css from 'css';
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.
css.parse
const css = require('css'); const ast = css.parse('body { color: red; }');
import { parse } from 'css';
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.
css.stringify
const css = require('css'); const cssString = css.stringify(ast);
import { stringify } from 'css';
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.

Demonstrates parsing CSS into an AST, stringifying it back, and generating compressed output or sourcemaps using the `css.parse` and `css.stringify` functions.

const css = require('css'); // Example CSS string const inputCss = ` /* This is a comment */ body { font-family: Arial, sans-serif; font-size: 16px; /* Default size */ color: #333; } @media (max-width: 600px) { body { font-size: 14px; } } `; // Parse the CSS string into an AST const ast = css.parse(inputCss, { source: 'example.css', // Recommended for better error messages and sourcemaps silent: false // Set to true to collect errors instead of throwing }); console.log('Parsed AST (partial):', JSON.stringify(ast.stylesheet.rules[0], null, 2)); // Stringify the AST back into CSS const outputCss = css.stringify(ast, { indent: ' ', // Use two spaces for indentation compress: false // Do not compress, maintain readability }); console.log('\nStringified CSS:\n', outputCss); // Stringify with compression const compressedCss = css.stringify(ast, { compress: true }); console.log('\nCompressed CSS:\n', compressedCss); // Example with sourcemap const resultWithMap = css.stringify(ast, { sourcemap: true, source: 'example.css' }); console.log('\nCSS with sourcemap (first 100 chars):\n', resultWithMap.code.substring(0, 100) + '...'); // console.log('Generated Sourcemap:', resultWithMap.map); // uncomment to see the map object
Debug
Known issues
gotchaWhen 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.
fix
After calling `css.parse` with `silent: true`, always check `ast.stylesheet.parsingErrors` for any `Error` objects and handle them appropriately.
affects: >=1.0.0
gotchaTo 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.
fix
Pass `source: 'your-filename.css'` as an option to `css.parse` when you intend to generate source maps later with `css.stringify`.
affects: >=1.0.0
gotchaThe `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.
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.
affects: >=3.0.0
breakingThe `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.
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.
affects: 3.x
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'parse')
The `css` module was not correctly loaded or returned an `undefined` or `null` object, preventing access to its methods.
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.
Parse error at <line>:<column>: <reason>
The input CSS string provided to `css.parse` contains syntax errors, is incomplete, or malformed according to CSS specifications.
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.
TypeError: Cannot read properties of null (reading 'type')
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`.
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.
Upgrade
Version history
1.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
12 hits · last 30 days
node
10
Resources