Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 19 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
[tests]: https://img.shields.io/circleci/project/github/shellscape/postcss-values-parser.svg
[tests-url]: https://circleci.com/gh/shellscape/postcss-values-parser
[cover]: https://codecov.io/gh/shellscape/postcss-values-parser/branch/master/graph/badge.svg
[cover-url]: https://codecov.io/gh/shellscape/postcss-values-parser
[actions]: https://github.com/shellscape/postcss-values-parser/actions/workflows/validate.yml/badge.svg?branch=master
[actions-url]: https://github.com/shellscape/postcss-values-parser/actions/workflows/validate.yml
[size]: https://packagephobia.now.sh/badge?p=postcss-values-parser
[size-url]: https://packagephobia.now.sh/result?p=postcss-values-parser

<div align="center">
<img width="95" height="95" title="Philosopher’s stone, logo of PostCSS" src="http://postcss.github.io/postcss/logo.svg"><br/><br/>
</div>

# postcss-values-parser [![tests][tests]][tests-url] [![cover][cover]][cover-url] [![size][size]][size-url]
# postcss-values-parser [![actions][actions]][actions-url] [![size][size]][size-url]

A CSS property value parser built upon [PostCSS](https://github.com/postcss/postcss),
following the same node and traversal patterns as PostCSS.
A CSS property value parser that uses [css-tree](https://github.com/csstree/csstree) for parsing,
and models nodes on top of PostCSS’s `Node`/`Container`/`Root` classes so the API feels familiar to PostCSS users.

This package powers part of [Prettier](https://prettier.io/). Please consider becoming a sponsor if you find this package useful or are a Prettier user. https://github.com/sponsors/shellscape

Expand All @@ -26,16 +24,24 @@ npm install postcss-values-parser --save-dev

## Requirements

`postcss-values-parser` Node version v6.14.0+ and PostCSS v7.0.0+.
- Node.js >= 20.19.0
- PostCSS >= 8.4.14 (peer dependency)

Note: This package is ESM‑only. Use `import` in Node.js. In CommonJS on Node >= 20.19.0, `require()` can load ES modules:

```js
// CommonJS (Node >= 20.19.0)
const { parse } = require('postcss-values-parser');
```

## Benefits

- Leverages PostCSS and its tokenizer under the hood
- Doesn't strip characters; eg. parenthesis
- Uses css-tree for fast, standards‑compliant parsing
- Builds PostCSS‑style nodes for a familiar API
- Doesn't strip characters; e.g., parentheses are preserved in the AST
- Full [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree) traversal
- Ability to walk the AST for every Node type
- Convenience methods to stringify Nodes
- Follows PostCSS patterns for whitespace between Nodes
- Optional walker helpers (`registerWalkers(Container)`) to walk by node type
- Convenience methods to stringify nodes
- Provides convenience properties for number units, colors, etc.

## Usage
Expand Down
7 changes: 3 additions & 4 deletions docs/Comment.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# Comment Node

The `Comment` node inherits directly from `Node` in PostCSS. This node represents a CSS comment; either inline (`//`) or block (`/* */`).
The `Comment` node inherits directly from `Node` in PostCSS. This node represents a CSS block comment (`/* … */`).

## Properties

### `inline`

Type: `Boolean`<br>

If `true`, indicates that the type of comment is "inline," or a comment that begins with `//`. If `false`, indicates that the comment is a traditional block comment.
Always `false` for CSS values. Inline `//` comments are not part of standard CSS values and are not produced by the parser.

### `text`

Expand All @@ -25,11 +25,10 @@ Value: `'comment'`

Type: `String`<br>

A `String` representation of the original comment including comment markers.
The original comment including comment markers, e.g. `/* comment */`.

## Example Values

```css
// na na na na na na na na batmannnnn
/* joker cheats at poker */
```
8 changes: 5 additions & 3 deletions docs/Container.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ This class inherits all properties and methods from PostCSS's `Container` class.
## Example Usage

```js
const { parse } = require('postcss-values-parser');
import { parse, Word } from 'postcss-values-parser';

const root = parse('calc(100px + 20%)');
const func = root.nodes[0]; // This is a Func node, which extends Container
Expand Down Expand Up @@ -85,7 +85,9 @@ Container nodes have access to all walker methods for traversing their child nod
- `walkType(type, callback)` - Walk through all nodes of a specific type

```js
const { parse } = require('postcss-values-parser');
import { parse, registerWalkers, Container } from 'postcss-values-parser';

registerWalkers(Container);

const root = parse('calc(100px + 20%) url("image.jpg")');
const func = root.nodes[0]; // calc function
Expand All @@ -108,5 +110,5 @@ See the [Walker](./Walker.md) documentation for more details on walker methods.
- Container nodes automatically handle source mapping and position tracking when nodes are added
- Child nodes maintain references to their parent container
- The Container class provides the foundation for complex nodes like `Func`, `Root`, and `Parentheses`
- Walker methods are registered automatically when the module is loaded
- Walker helpers must be registered once via `registerWalkers(Container)` before use
- Walker methods traverse all descendants, not just direct children
19 changes: 2 additions & 17 deletions docs/Examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -333,22 +333,7 @@ root.walkWords((word) => {
});
```

### SCSS/LESS Variables

```js
const { parse } = require('postcss-values-parser');

// Parse SCSS variables
const root = parse('$primary-color', {
variables: { prefixes: ['--', '$'] }
});

root.walkWords((word) => {
if (word.isVariable) {
console.log(`SCSS Variable: ${word.value}`);
}
});
```
> Note: In v7, `Word.isVariable` only detects CSS custom properties (values starting with `--`). SCSS/LESS variable prefixes are not detected.

## Error Handling

Expand Down Expand Up @@ -627,4 +612,4 @@ describe('Value Parser', () => {
- Consider caching parsed results for frequently used values
- Custom stringifiers allow for powerful value transformations
- The parser preserves source mapping information for debugging
- All examples can be adapted for use in various build tools and frameworks
- All examples can be adapted for use in various build tools and frameworks
82 changes: 16 additions & 66 deletions docs/Exports.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# Exported Methods
# Exported API

This module exports the following methods and classes:

### `parse(css, options)`
### `parse(css, options?)`

Returns: `Root`<br>

Parses a given `String` and returns an AST with a `Root` node. If the input is an invalid CSS value, a `ParseError` is thrown.
Parses a given string and returns an AST with a `Root` node. If the input is an invalid CSS value, a `ParseError` is thrown.

#### Parameters

Expand All @@ -17,36 +17,13 @@ _Required_

#### `options`

Type: `ParseOptions`<br>
_Optional_
Type: `ParseOptions` (optional)

##### Properties

##### `ignoreUnknownWords`

Type: `Boolean`<br>
Default: `false`

If `true`, will allow all unknown parts of the value to be parsed and added to the AST. If `false`, unknown values will throw `ParseError`.

##### `interpolation`

Type: `Boolean|InterpolationOptions`<br>
Default: `false`

Set this option to enable parsing of interpolated values for languages such as SCSS. For example:
`interpolation: { prefix: '@' }` will allow parsing of the interpolated value `@{batman}` which uses `@` as the "prefix". For SCSS one might use `interpolation: { prefix: '#' }`.

##### `variables`

Type: `VariablesOptions`<br>
Default: `{ prefixes: ['--'] }`

Set this option to modify how variables are identified in a value. By default, this option is set to recognize CSS variables. For languages such as LESS and SCSS which have their own variable prefixes, additional prefixes can be added to the `prefixes` array.
Reserved for future use. In v7, options are accepted by the signature but are not used by the parser.

### `stringify(node, builder)`

A `Function` with a signature matching `(bit) => {}` used to concatenate or manipulate each portion (or bit) of the Node's own AST. The `nodeToString` method makes use of this, as a simple example.
A function used to concatenate or manipulate each portion (or bit) of a node during stringification. The `nodeToString` helper uses this under the hood.

#### Parameters

Expand Down Expand Up @@ -79,7 +56,7 @@ Returns: `String`

### `registerWalkers(Container)`

Registers custom walker methods on the Container prototype to enable walking specific node types. This function is called automatically when the module is loaded, but can be called manually if needed.
Registers custom walker methods on the Container prototype to enable walking specific node types. This function is not called automatically; call it once before using any `walk*` helpers.

#### Parameters

Expand All @@ -92,7 +69,7 @@ The Container class to register walker methods on.

## Exported Classes

All Node classes are exported and can be imported individually:
All node classes are exported and can be imported individually:

### Node Classes

Expand All @@ -116,40 +93,16 @@ All Node classes are exported and can be imported individually:

### Type Definitions

- `ParseOptions` - Options interface for the parse function
- `InterpolationOptions` - Options for interpolation parsing
- `VariablesOptions` - Options for variable recognition
- `ParseOptions` - Placeholder in v7 (forward‑compatibility)
- `Stringifier` - Function interface for custom stringifiers
- `Builder` - Function interface for string building during stringify
- `NodeOptions` - Options interface for node construction

## Type Interfaces
## Types

### `ParseOptions`

```typescript
interface ParseOptions {
ignoreUnknownWords?: boolean;
interpolation?: boolean | InterpolationOptions;
variables?: VariablesOptions;
}
```

### `InterpolationOptions`

```typescript
interface InterpolationOptions {
prefix: string;
}
```

### `VariablesOptions`

```typescript
interface VariablesOptions {
prefixes: string[];
}
```
An empty placeholder interface in v7. Kept for forward‑compatibility.

### `Stringifier`

Expand Down Expand Up @@ -181,19 +134,16 @@ interface NodeOptions {

```js
// Import specific classes
const { parse, Node, Container, Root } = require('postcss-values-parser');
import { parse, Node, Container, Root } from 'postcss-values-parser';

// Import error classes
const { ParseError, AstError } = require('postcss-values-parser');
import { ParseError, AstError } from 'postcss-values-parser';

// Import utility functions
const { stringify, nodeToString, registerWalkers } = require('postcss-values-parser');
import { stringify, nodeToString, registerWalkers } from 'postcss-values-parser';

// Parse with options
const root = parse('calc(100px + 20%)', {
ignoreUnknownWords: true,
variables: { prefixes: ['--', '$'] }
});
// Parse
const root = parse('calc(100px + 20%)');

// Custom stringifier
const customStringifier = (node, builder) => {
Expand Down
4 changes: 2 additions & 2 deletions docs/Node.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ This class inherits all properties and methods from PostCSS's `Node` class. Plea
## Example Usage

```js
const { parse, Word } = require('postcss-values-parser');
import { parse, Word } from 'postcss-values-parser';

const root = parse('bold italic');
const firstNode = root.nodes[0];
Expand All @@ -78,4 +78,4 @@ console.log(newNode.value); // 'underline'
- All nodes automatically maintain parent-child relationships when added to containers
- Source mapping information is preserved throughout parsing and manipulation
- The Node class provides the foundation for all AST traversal and manipulation operations
- The `value` property is readonly and should be set during construction via the options parameter
- The `value` property is readonly and should be set during construction via the options parameter
4 changes: 2 additions & 2 deletions docs/Parentheses.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ This class inherits all properties and methods from the `Container` class and Po
## Example Usage

```js
const { parse } = require('postcss-values-parser');
import { parse } from 'postcss-values-parser';

const root = parse('calc((100px + 20px) * 2)');
const func = root.nodes[0]; // calc function
Expand All @@ -85,4 +85,4 @@ parentheses.nodes.forEach(node => {
- Parentheses nodes are automatically created when the parser encounters parentheses groupings in CSS values
- The content within parentheses is parsed as separate child nodes
- Parentheses nodes maintain the structural integrity of grouped expressions
- They are commonly found within function arguments and mathematical expressions
- They are commonly found within function arguments and mathematical expressions
Loading