Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

Index

Constructors

Properties

nodes: ChildNode[]

An array containing the container’s children.

const root = postcss.parse('a { color: black }')
root.nodes.length //=> 1
root.nodes[0].selector //=> 'a'
root.nodes[0].nodes[0].prop //=> 'color'
parent: undefined | Document_

It represents parent of the current node.

root.nodes[0].parent === root //=> true
raws: RootRaws

It represents unnecessary whitespace and characters present in the css source code.

Information to generate byte-to-byte equal node string as it was in the origin input.

The properties of the raws object are decided by parser, the default parser uses the following properties:

  • before: the space symbols before the node. It also stores * and _ symbols before the declaration (IE hack).
  • after: the space symbols after the last child of the node to the end of the node.
  • between: the symbols between the property and value for declarations, selector and { for rules, or last parameter and { for at-rules.
  • semicolon: contains true if the last child has an (optional) semicolon.
  • afterName: the space between the at-rule name and its parameters.
  • left: the space symbols between /* and the comment’s text.
  • right: the space symbols between the comment’s text and */.
  • important: the content of the important statement, if it is not just !important.

PostCSS filters out the comments inside selectors, declaration values and at-rule parameters but it stores the origin content in raws.

const root = postcss.parse('a {\n  color:black\n}')
root.first.first.raws //=> { before: '\n ', between: ':' }
source?: Source

It represents information related to origin of a node and is required for generating source maps.

The nodes that are created manually using the public APIs provided by PostCSS will have source undefined and will be absent in the source map.

For this reason, the plugin developer should consider duplicating nodes as the duplicate node will have the same source as the original node by default or assign source to a node created manually.

decl.source.input.from //=> '/home/ai/source.css'
decl.source.start //=> { line: 10, column: 2 }
decl.source.end //=> { line: 10, column: 12 }
// Incorrect method, source not specified!
const prefixed = postcss.decl({
prop: '-moz-' + decl.prop,
value: decl.value
})

// Correct method, source is inherited when duplicating.
const prefixed = decl.clone({
prop: '-moz-' + decl.prop
})
if (atrule.name === 'add-link') {
const rule = postcss.rule({
selector: 'a',
source: atrule.source
})

atrule.parent.insertBefore(atrule, rule)
}
type: "root"

It represents type of a node in an abstract syntax tree.

A type of node helps in identification of a node and perform operation based on it's type.

const declaration = new Declaration({
prop: 'color',
value: 'black'
})

declaration.type //=> 'decl'

Accessors

  • get first(): undefined | Child
  • The container’s first child.

    rule.first === rules.nodes[0]
    

    Returns undefined | Child

  • get last(): undefined | Child
  • The container’s last child.

    rule.last === rule.nodes[rule.nodes.length - 1]
    

    Returns undefined | Child

Methods

  • Insert new node after current node to current node’s parent.

    Just alias for node.parent.insertAfter(node, add).

    decl.after('color: black')
    

    Parameters

    Returns Root

    This node for methods chain.

  • Inserts new nodes to the end of the container.

    const decl1 = new Declaration({ prop: 'color', value: 'black' })
    const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
    rule.append(decl1, decl2)

    root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
    root.append({ selector: 'a' }) // rule
    rule.append({ prop: 'color', value: 'black' }) // declaration
    rule.append({ text: 'Comment' }) // comment

    root.append('a {}')
    root.first.append('color: black; z-index: 1')

    Parameters

    Returns Root

    This node for methods chain.

  • It assigns properties to an existing node instance.

    decl.assign({ prop: 'word-wrap', value: 'break-word' })
    

    Parameters

    Returns Root

    this for method chaining.

  • Insert new node before current node to current node’s parent.

    Just alias for node.parent.insertBefore(node, add).

    decl.before('content: ""')
    

    Parameters

    Returns Root

    This node for methods chain.

  • cleanRaws(keepBetween?: boolean): void
  • Clear the code style properties for the node and its children.

    node.raws.before  //=> ' '
    node.cleanRaws()
    node.raws.before //=> undefined

    Parameters

    • Optional keepBetween: boolean

      Keep the raws.between symbols.

    Returns void

  • It creates clone of an existing node, which includes all the properties and their values, that includes raws but not type.

    decl.raws.before    //=> "\n  "
    const cloned = decl.clone({ prop: '-moz-' + decl.prop })
    cloned.raws.before //=> "\n "
    cloned.toString() //=> -moz-transform: scale(0)

    Parameters

    Returns Root

    Duplicate of the node instance.

  • Shortcut to clone the node and insert the resulting cloned node after the current node.

    Parameters

    Returns Root

    New node.

  • Shortcut to clone the node and insert the resulting cloned node before the current node.

    decl.cloneBefore({ prop: '-moz-' + decl.prop })
    

    Parameters

    Returns Root

    New node

  • each(callback: (node: ChildNode, index: number) => false | void): undefined | false
  • Iterates through the container’s immediate children, calling callback for each child.

    Returning false in the callback will break iteration.

    This method only iterates through the container’s immediate children. If you need to recursively iterate through all the container’s descendant nodes, use Container#walk.

    Unlike the for {}-cycle or Array#forEach this iterator is safe if you are mutating the array of child nodes during iteration. PostCSS will adjust the current index to match the mutations.

    const root = postcss.parse('a { color: black; z-index: 1 }')
    const rule = root.first

    for (const decl of rule.nodes) {
    decl.cloneBefore({ prop: '-webkit-' + decl.prop })
    // Cycle will be infinite, because cloneBefore moves the current node
    // to the next index
    }

    rule.each(decl => {
    decl.cloneBefore({ prop: '-webkit-' + decl.prop })
    // Will be executed only for color and z-index
    })

    Parameters

    • callback: (node: ChildNode, index: number) => false | void

      Iterator receives each node and index.

        • (node: ChildNode, index: number): false | void
        • Parameters

          Returns false | void

    Returns undefined | false

    Returns false if iteration was broke.

  • It creates an instance of the class CssSyntaxError and parameters passed to this method are assigned to the error instance.

    The error instance will have description for the error, original position of the node in the source, showing line and column number.

    If any previous map is present, it would be used to get original position of the source.

    The Previous Map here is referred to the source map generated by previous compilation, example: Less, Stylus and Sass.

    This method returns the error instance instead of throwing it.

    if (!variables[name]) {
    throw decl.error(`Unknown variable ${name}`, { word: name })
    // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
    // color: $black
    // a
    // ^
    // background: white
    }

    Parameters

    • message: string

      Description for the error instance.

    • Optional options: Node.NodeErrorOptions

      Options for the error instance.

    Returns CssSyntaxError_

    Error instance is returned.

  • every(condition: (node: ChildNode, index: number, nodes: ChildNode[]) => boolean): boolean
  • Returns true if callback returns true for all of the container’s children.

    const noPrefixes = rule.every(i => i.prop[0] !== '-')
    

    Parameters

    Returns boolean

    Is every child pass condition.

  • Returns a child’s index within the Container#nodes array.

    rule.index( rule.nodes[2] ) //=> 2
    

    Parameters

    • child: number | ChildNode

      Child of the current container.

    Returns number

    Child index.

  • Insert new node after old node within the container.

    Parameters

    Returns Root

    This node for methods chain.

  • Insert new node before old node within the container.

    rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
    

    Parameters

    Returns Root

    This node for methods chain.

  • Returns the next child of the node’s parent. Returns undefined if the current node is the last child.

    if (comment.text === 'delete next') {
    const next = comment.next()
    if (next) {
    next.remove()
    }
    }

    Returns undefined | ChildNode

    Next node.

  • Get the position for a word or an index inside the node.

    Parameters

    Returns Position

    Position.

  • Convert string index to line/column.

    Parameters

    • index: number

      The symbol number in the node’s string.

    Returns Position

    Symbol position in file.

  • Inserts new nodes to the start of the container.

    const decl1 = new Declaration({ prop: 'color', value: 'black' })
    const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
    rule.prepend(decl1, decl2)

    root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
    root.append({ selector: 'a' }) // rule
    rule.append({ prop: 'color', value: 'black' }) // declaration
    rule.append({ text: 'Comment' }) // comment

    root.append('a {}')
    root.first.append('color: black; z-index: 1')

    Parameters

    Returns Root

    This node for methods chain.

  • Returns the previous child of the node’s parent. Returns undefined if the current node is the first child.

    const annotation = decl.prev()
    if (annotation.type === 'comment') {
    readAnnotation(annotation.text)
    }

    Returns undefined | ChildNode

    Previous node.

  • Add child to the end of the node.

    rule.push(new Declaration({ prop: 'color', value: 'black' }))
    

    Parameters

    Returns Root

    This node for methods chain.

  • Get the range for a word or start and end index inside the node. The start index is inclusive; the end index is exclusive.

    Parameters

    • Optional opts: Pick<WarningOptions, "index" | "word" | "endIndex">

      Options.

    Returns Range

    Range.

  • raw(prop: string, defaultType?: string): string
  • Returns a raws value. If the node is missing the code style property (because the node was manually built or cloned), PostCSS will try to autodetect the code style property by looking at other nodes in the tree.

    const root = postcss.parse('a { background: white }')
    root.nodes[0].append({ prop: 'color', value: 'black' })
    root.nodes[0].nodes[1].raws.before //=> undefined
    root.nodes[0].nodes[1].raw('before') //=> ' '

    Parameters

    • prop: string

      Name of code style property.

    • Optional defaultType: string

      Name of default value, it can be missed if the value is the same as prop.

    Returns string

    Code style value.

  • It removes the node from its parent and deletes its parent property.

    if (decl.prop.match(/^-webkit-/)) {
    decl.remove()
    }

    Returns Root

    this for method chaining.

  • Removes all children from the container and cleans their parent properties.

    rule.removeAll()
    rule.nodes.length //=> 0

    Returns Root

    This node for methods chain.

  • Removes node from the container and cleans the parent properties from the node and its children.

    rule.nodes.length  //=> 5
    rule.removeChild(decl)
    rule.nodes.length //=> 4
    decl.parent //=> undefined

    Parameters

    • child: number | ChildNode

      Child or child’s index.

    Returns Root

    This node for methods chain.

  • replaceValues(pattern: string | RegExp, replaced: string | ((substring: string, ...args: any[]) => string)): Root
  • replaceValues(pattern: string | RegExp, options: ValueOptions, replaced: string | ((substring: string, ...args: any[]) => string)): Root
  • Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.

    This method is useful if you are using a custom unit or function and need to iterate through all values.

    root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
    return 15 * parseInt(string) + 'px'
    })

    Parameters

    • pattern: string | RegExp

      Replace pattern.

    • replaced: string | ((substring: string, ...args: any[]) => string)

    Returns Root

    This node for methods chain.

  • Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.

    This method is useful if you are using a custom unit or function and need to iterate through all values.

    root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
    return 15 * parseInt(string) + 'px'
    })

    Parameters

    • pattern: string | RegExp

      Replace pattern.

    • options: ValueOptions
    • replaced: string | ((substring: string, ...args: any[]) => string)

    Returns Root

    This node for methods chain.

  • Inserts node(s) before the current node and removes the current node.

    AtRule: {
    mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
    }
    }

    Parameters

    Returns Root

    Current node to methods chain.

  • Finds the Root instance of the node’s tree.

    root.nodes[0].nodes[0].root() === root
    

    Returns Root_

    Root parent.

  • Returns true if callback returns true for (at least) one of the container’s children.

    const hasPrefix = rule.some(i => i.prop[0] === '-')
    

    Parameters

    Returns boolean

    Is some child pass condition.

  • toJSON(): object
  • Fix circular links on JSON.stringify().

    Returns object

    Cleaned object.

  • Returns a Result instance representing the root’s CSS.

    const root1 = postcss.parse(css1, { from: 'a.css' })
    const root2 = postcss.parse(css2, { from: 'b.css' })
    root1.append(root2)
    const result = root1.toResult({ to: 'all.css', map: true })

    Parameters

    Returns Result_<Document_ | Root_>

    Result with current root’s CSS.

  • It compiles the node to browser readable cascading style sheets string depending on it's type.

    new Rule({ selector: 'a' }).toString() //=> "a {}"
    

    Parameters

    Returns string

    CSS string of this node.

  • walk(callback: (node: ChildNode, index: number) => false | void): undefined | false
  • Traverses the container’s descendant nodes, calling callback for each node.

    Like container.each(), this method is safe to use if you are mutating arrays during iteration.

    If you only need to iterate through the container’s immediate children, use Container#each.

    root.walk(node => {
    // Traverses all descendant nodes.
    })

    Parameters

    • callback: (node: ChildNode, index: number) => false | void

      Iterator receives each node and index.

        • (node: ChildNode, index: number): false | void
        • Parameters

          Returns false | void

    Returns undefined | false

    Returns false if iteration was broke.

  • walkAtRules(nameFilter: string | RegExp, callback: (atRule: AtRule_, index: number) => false | void): undefined | false
  • walkAtRules(callback: (atRule: AtRule_, index: number) => false | void): undefined | false
  • Traverses the container’s descendant nodes, calling callback for each at-rule node.

    If you pass a filter, iteration will only happen over at-rules that have matching names.

    Like Container#each, this method is safe to use if you are mutating arrays during iteration.

    root.walkAtRules(rule => {
    if (isOld(rule.name)) rule.remove()
    })

    let first = false
    root.walkAtRules('charset', rule => {
    if (!first) {
    first = true
    } else {
    rule.remove()
    }
    })

    Parameters

    • nameFilter: string | RegExp
    • callback: (atRule: AtRule_, index: number) => false | void

      Iterator receives each node and index.

        • (atRule: AtRule_, index: number): false | void
        • Parameters

          Returns false | void

    Returns undefined | false

    Returns false if iteration was broke.

  • Parameters

    • callback: (atRule: AtRule_, index: number) => false | void
        • (atRule: AtRule_, index: number): false | void
        • Parameters

          Returns false | void

    Returns undefined | false

  • walkComments(callback: (comment: Comment_, indexed: number) => false | void): undefined | false
  • walkComments(callback: (comment: Comment_, indexed: number) => false | void): undefined | false
  • Parameters

    • callback: (comment: Comment_, indexed: number) => false | void
        • (comment: Comment_, indexed: number): false | void
        • Parameters

          Returns false | void

    Returns undefined | false

  • Parameters

    • callback: (comment: Comment_, indexed: number) => false | void
        • (comment: Comment_, indexed: number): false | void
        • Parameters

          Returns false | void

    Returns undefined | false

  • walkDecls(propFilter: string | RegExp, callback: (decl: Declaration_, index: number) => false | void): undefined | false
  • walkDecls(callback: (decl: Declaration_, index: number) => false | void): undefined | false
  • Traverses the container’s descendant nodes, calling callback for each declaration node.

    If you pass a filter, iteration will only happen over declarations with matching properties.

    root.walkDecls(decl => {
    checkPropertySupport(decl.prop)
    })

    root.walkDecls('border-radius', decl => {
    decl.remove()
    })

    root.walkDecls(/^background/, decl => {
    decl.value = takeFirstColorFromGradient(decl.value)
    })

    Like Container#each, this method is safe to use if you are mutating arrays during iteration.

    Parameters

    • propFilter: string | RegExp
    • callback: (decl: Declaration_, index: number) => false | void

      Iterator receives each node and index.

    Returns undefined | false

    Returns false if iteration was broke.

  • Parameters

    Returns undefined | false

  • walkRules(selectorFilter: string | RegExp, callback: (rule: Rule_, index: number) => false | void): undefined | false
  • walkRules(callback: (rule: Rule_, index: number) => false | void): undefined | false
  • Traverses the container’s descendant nodes, calling callback for each rule node.

    If you pass a filter, iteration will only happen over rules with matching selectors.

    Like Container#each, this method is safe to use if you are mutating arrays during iteration.

    const selectors = []
    root.walkRules(rule => {
    selectors.push(rule.selector)
    })
    console.log(`Your CSS uses ${ selectors.length } selectors`)

    Parameters

    • selectorFilter: string | RegExp
    • callback: (rule: Rule_, index: number) => false | void

      Iterator receives each node and index.

        • (rule: Rule_, index: number): false | void
        • Parameters

          Returns false | void

    Returns undefined | false

    Returns false if iteration was broke.

  • Parameters

    • callback: (rule: Rule_, index: number) => false | void
        • (rule: Rule_, index: number): false | void
        • Parameters

          Returns false | void

    Returns undefined | false

  • It is a wrapper for {@link Result#warn}, providing convenient way of generating warnings.

      Declaration: {
    bad: (decl, { result }) => {
    decl.warn(result, 'Deprecated property: bad')
    }
    }

    Parameters

    • result: Result_<Document_ | Root_>

      The Result instance that will receive the warning.

    • message: string

      Description for the warning.

    • Optional options: WarningOptions

      Options for the warning.

    Returns Warning_

    Warning instance is returned