postcss

Create a new Processor instance that will apply plugins as CSS processors.

let postcss = require('postcss')

postcss(plugins).process(css, { from, to }).then(result => {
  console.log(result.css)
})
ArgumentTypeDescription
pluginsAcceptedPlugin[]PostCSS plugins.
ArgumentTypeDescription
plugins…AcceptedPlugin[]PostCSS plugins.

Returns Processor. Processor to process multiple CSS.

postcss.AtRule

Type: typeof AtRule.

postcss.Comment

Type: typeof Comment.

postcss.Container

Type: typeof Container.

postcss.CssSyntaxError

Type: typeof CssSyntaxError.

postcss.Declaration

Type: typeof Declaration.

postcss.Input

Type: typeof Input.

postcss.Node

Type: typeof Node.

postcss.Result

Type: typeof Result.

postcss.Root

Type: typeof Root.

postcss.Rule

Type: typeof Rule.

postcss.Warning

Type: typeof Warning.

postcss.list

Contains the list module.

Type: List.

postcss.parse

Parses source css and returns a new Root node, which contains the source CSS nodes.

// Simple CSS concatenation with source map support
const root1 = postcss.parse(css1, { from: file1 })
const root2 = postcss.parse(css2, { from: file2 })
root1.append(root2).toResult().css

Type: Parser.

postcss.stringify

Default function to convert a node tree into a CSS string.

Type: Stringifier.

postcss.atRule()

Creates a new AtRule node.

ArgumentTypeDescription
defaultsAtRulePropsProperties for the new node.

Returns AtRule. New at-rule node.

postcss.comment()

Creates a new Comment node.

ArgumentTypeDescription
defaultsCommentPropsProperties for the new node.

Returns Comment. New comment node

postcss.decl()

Creates a new Declaration node.

ArgumentTypeDescription
defaultsDeclarationPropsProperties for the new node.

Returns Declaration. New declaration node.

postcss.root()

Creates a new Root node.

ArgumentTypeDescription
defaultsRootPropsProperties for the new node.

Returns Root. New root node.

postcss.rule()

Creates a new Rule node.

ArgumentType
defaultsRuleProps

Returns Rule. New rule node.

AtRule

Represents an at-rule.

Once (root, { AtRule }) {
  let media = new AtRule({ name: 'media', params: 'print' })
  media.append(…)
  root.append(media)
}

If it’s followed in the CSS by a {} block, this node will have a nodes property representing its children.

const root = postcss.parse('@charset "UTF-8"; @media print {}')

const charset = root.first
charset.type  //=> 'atrule'
charset.nodes //=> undefined

const media = root.last
media.nodes   //=> []

AtRule#name

The at-rule’s name immediately follows the @.

const root  = postcss.parse('@media print {}')
media.name //=> 'media'
const media = root.first

Type: string.

AtRule#nodes

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'

Type: ChildNode[].

AtRule#params

The at-rule’s parameters, the values that follow the at-rule’s name but precede any {} block.

const root  = postcss.parse('@media print, screen {}')
const media = root.first
media.params //=> 'print, screen'

Type: string.

AtRule#parent

The node’s parent node.

root.nodes[0].parent === root

Type: Container | undefined.

AtRule#raws

Type: AtRuleRaws.

AtRule#source

The input source of the node.

The property is used in source map generation.

If you create a node manually (e.g., with postcss.decl()), that node will not have a source property and will be absent from the source map. For this reason, the plugin developer should consider cloning nodes to create new ones (in which case the new node’s source will reference the original, cloned node) or setting the source property manually.

decl.source.input.from //=> '/home/ai/a.sass'
decl.source.start      //=> { line: 10, column: 2 }
decl.source.end        //=> { line: 10, column: 12 }
// Bad
const prefixed = postcss.decl({
  prop: '-moz-' + decl.prop,
  value: decl.value
})

// Good
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: Source.

AtRule#type

Type: "atrule".

AtRule#first

The container’s first child.

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

AtRule#last

The container’s last child.

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

AtRule#after()

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

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

decl.after('color: black')
ArgumentTypeDescription
newNodeNode | ChildProps | string | Node[]New node.

Returns itself for methods chain.

AtRule#append()

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')
ArgumentTypeDescription
nodes…(Node | Node[] | ChildProps | ChildProps[] | string | string[])[]New nodes.

Returns itself for methods chain.

AtRule#before()

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

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

decl.before('content: ""')
ArgumentTypeDescription
newNodeNode | ChildProps | string | Node[]New node.

Returns itself for methods chain.

AtRule#cleanRaws()

Clear the code style properties for the node and its children.

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
ArgumentTypeDescription
keepBetweenbooleanKeep the raws.between symbols.

AtRule#clone()

ArgumentTypeDescription
overridesPartial<AtRuleProps>New properties to override in the clone.

Returns itself for methods chain.

AtRule#cloneAfter()

ArgumentTypeDescription
overridesPartial<AtRuleProps>New properties to override in the clone.

Returns itself for methods chain.

AtRule#cloneBefore()

ArgumentTypeDescription
overridesPartial<AtRuleProps>Mew properties to override in the clone.

Returns itself for methods chain.

AtRule#each()

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
})
ArgumentTypeDescription
callback(node: ChildNode, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

AtRule#error()

Returns a CssSyntaxError instance containing the original position of the node in the source, showing line and column numbers and also a small excerpt to facilitate debugging.

If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).

This method produces very useful error messages.

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
}
ArgumentTypeDescription
messagestringError description.
optionsNodeErrorOptions

Returns CssSyntaxError. Error object to throw it.

AtRule#every()

Returns true if callback returns true for all of the container’s children.

const noPrefixes = rule.every(i => i.prop[0] !== '-')
ArgumentTypeDescription
condition(node: ChildNode, index: number, nodes: ChildNode[]) => booleanIterator returns true or false.

Returns boolean. Is every child pass condition.

AtRule#index()

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

rule.index( rule.nodes[2] ) //=> 2
ArgumentTypeDescription
childChildNode | numberChild of the current container.

Returns number. Child index.

AtRule#insertAfter()

Insert new node after old node within the container.

ArgumentTypeDescription
oldNodeChildNode | numberChild or child’s index.
newNodeChildNode | ChildProps | string | ChildNode[] | ChildProps[] | string[]New node.

Returns itself for methods chain.

AtRule#insertBefore()

Insert new node before old node within the container.

rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
ArgumentTypeDescription
oldNodeChildNode | numberChild or child’s index.
newNodeChildNode | ChildProps | string | ChildNode[] | ChildProps[] | string[]New node.

Returns itself for methods chain.

AtRule#next()

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 ChildNode | undefined. Next node.

AtRule#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position. Symbol position in file.

AtRule#prepend()

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')
ArgumentTypeDescription
nodes…(Node | Node[] | ChildProps | ChildProps[] | string | string[])[]New nodes.

Returns itself for methods chain.

AtRule#prev()

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 ChildNode | undefined. Previous node.

AtRule#push()

Add child to the end of the node.

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

Returns itself for methods chain.

AtRule#raw()

Returns a Node#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') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string. Code style value.

AtRule#remove()

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

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

Returns itself for methods chain.

AtRule#removeAll()

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

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

Returns itself for methods chain.

AtRule#removeChild()

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
ArgumentTypeDescription
childChildNode | numberChild or child’s index.

Returns itself for methods chain.

AtRule#replaceValues()

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'
})
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
optionsValueOptions
replacedstring | (substring: string, args: any[]) => string
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
replacedstring | (substring: string, args: any[]) => string

Returns itself for methods chain.

AtRule#replaceWith()

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

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
ArgumentTypeDescription
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]Mode(s) to replace current one.

Returns itself for methods chain.

AtRule#root()

Finds the Root instance of the node’s tree.

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

Returns Root. Root parent.

AtRule#some()

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

const hasPrefix = rule.some(i => i.prop[0] === '-')
ArgumentTypeDescription
condition(node: ChildNode, index: number, nodes: ChildNode[]) => booleanIterator returns true or false.

Returns boolean. Is some child pass condition.

AtRule#toJSON()

Fix circular links on JSON.stringify().

Returns object. Cleaned object.

AtRule#toString()

Returns a CSS string representing the node.

new Rule({ selector: 'a' }).toString() //=> "a {}"
ArgumentTypeDescription
stringifierStringifier | SyntaxA syntax to use in string generation.

Returns string. CSS string of this node.

AtRule#walk()

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.
})
ArgumentTypeDescription
callback(node: ChildNode, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

AtRule#walkAtRules()

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()
  }
})
ArgumentTypeDescription
nameFilterstring | RegExp
callback(atRule: AtRule, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

AtRule#walkComments()

Traverses the container’s descendant nodes, calling callback for each comment node.

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

root.walkComments(comment => {
  comment.remove()
})
ArgumentTypeDescription
callback(comment: Comment, indexed: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

AtRule#walkDecls()

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.

ArgumentTypeDescription
propFilterstring | RegExp
callback(decl: Declaration, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

AtRule#walkRules()

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`)
ArgumentTypeDescription
selectorFilterstring | RegExp
callback(atRule: Rule, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

AtRule#warn()

This method is provided as a convenience wrapper for Result#warn.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property bad')
    }
  }
ArgumentTypeDescription
resultResultThe Result instance that will receive the warning.
textstringWarning message.
optsWarningOptionsWarning Options.

Comment

Represents a comment between declarations or statements (rule and at-rules).

Once (root, { Comment }) {
  let note = new Comment({ text: 'Note: …' })
  root.append(note)
}

Comments inside selectors, at-rule parameters, or declaration values will be stored in the raws properties explained above.

Comment#parent

The node’s parent node.

root.nodes[0].parent === root

Type: Container | undefined.

Comment#raws

Type: CommentRaws.

Comment#source

The input source of the node.

The property is used in source map generation.

If you create a node manually (e.g., with postcss.decl()), that node will not have a source property and will be absent from the source map. For this reason, the plugin developer should consider cloning nodes to create new ones (in which case the new node’s source will reference the original, cloned node) or setting the source property manually.

decl.source.input.from //=> '/home/ai/a.sass'
decl.source.start      //=> { line: 10, column: 2 }
decl.source.end        //=> { line: 10, column: 12 }
// Bad
const prefixed = postcss.decl({
  prop: '-moz-' + decl.prop,
  value: decl.value
})

// Good
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: Source.

Comment#text

The comment's text.

Type: string.

Comment#type

Type: "comment".

Comment#after()

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

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

decl.after('color: black')
ArgumentTypeDescription
newNodeNode | ChildProps | string | Node[]New node.

Returns itself for methods chain.

Comment#before()

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

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

decl.before('content: ""')
ArgumentTypeDescription
newNodeNode | ChildProps | string | Node[]New node.

Returns itself for methods chain.

Comment#cleanRaws()

Clear the code style properties for the node and its children.

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
ArgumentTypeDescription
keepBetweenbooleanKeep the raws.between symbols.

Comment#clone()

ArgumentTypeDescription
overridesPartial<CommentProps>New properties to override in the clone.

Returns itself for methods chain.

Comment#cloneAfter()

ArgumentTypeDescription
overridesPartial<CommentProps>New properties to override in the clone.

Returns itself for methods chain.

Comment#cloneBefore()

ArgumentTypeDescription
overridesPartial<CommentProps>Mew properties to override in the clone.

Returns itself for methods chain.

Comment#error()

Returns a CssSyntaxError instance containing the original position of the node in the source, showing line and column numbers and also a small excerpt to facilitate debugging.

If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).

This method produces very useful error messages.

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
}
ArgumentTypeDescription
messagestringError description.
optionsNodeErrorOptions

Returns CssSyntaxError. Error object to throw it.

Comment#next()

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 ChildNode | undefined. Next node.

Comment#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position. Symbol position in file.

Comment#prev()

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 ChildNode | undefined. Previous node.

Comment#raw()

Returns a Node#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') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string. Code style value.

Comment#remove()

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

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

Returns itself for methods chain.

Comment#replaceWith()

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

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
ArgumentTypeDescription
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]Mode(s) to replace current one.

Returns itself for methods chain.

Comment#root()

Finds the Root instance of the node’s tree.

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

Returns Root. Root parent.

Comment#toJSON()

Fix circular links on JSON.stringify().

Returns object. Cleaned object.

Comment#toString()

Returns a CSS string representing the node.

new Rule({ selector: 'a' }).toString() //=> "a {}"
ArgumentTypeDescription
stringifierStringifier | SyntaxA syntax to use in string generation.

Returns string. CSS string of this node.

Comment#warn()

This method is provided as a convenience wrapper for Result#warn.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property bad')
    }
  }
ArgumentTypeDescription
resultResultThe Result instance that will receive the warning.
textstringWarning message.
optsWarningOptionsWarning Options.

Container

The Root, AtRule, and Rule container nodes inherit some common methods to help work with their children.

Note that all containers can store any content. If you write a rule inside a rule, PostCSS will parse it.

Container#nodes

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'

Type: ChildNode[].

Container#parent

The node’s parent node.

root.nodes[0].parent === root

Type: Container | undefined.

Container#raws

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

Every parser saves its own properties, but the default CSS parser uses:

PostCSS cleans selectors, declaration values and at-rule parameters from comments and extra spaces, but it stores origin content in raws properties. As such, if you don’t change a declaration’s value, PostCSS will use the raw value with comments.

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

Type: any.

Container#source

The input source of the node.

The property is used in source map generation.

If you create a node manually (e.g., with postcss.decl()), that node will not have a source property and will be absent from the source map. For this reason, the plugin developer should consider cloning nodes to create new ones (in which case the new node’s source will reference the original, cloned node) or setting the source property manually.

decl.source.input.from //=> '/home/ai/a.sass'
decl.source.start      //=> { line: 10, column: 2 }
decl.source.end        //=> { line: 10, column: 12 }
// Bad
const prefixed = postcss.decl({
  prop: '-moz-' + decl.prop,
  value: decl.value
})

// Good
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: Source.

Container#type

tring representing the node’s type. Possible values are root, atrule, rule, decl, or comment.

new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'

Type: string.

Container#first

The container’s first child.

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

Container#last

The container’s last child.

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

Container#after()

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

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

decl.after('color: black')
ArgumentTypeDescription
newNodeNode | ChildProps | string | Node[]New node.

Returns itself for methods chain.

Container#append()

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')
ArgumentTypeDescription
nodes…(Node | Node[] | ChildProps | ChildProps[] | string | string[])[]New nodes.

Returns itself for methods chain.

Container#before()

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

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

decl.before('content: ""')
ArgumentTypeDescription
newNodeNode | ChildProps | string | Node[]New node.

Returns itself for methods chain.

Container#cleanRaws()

Clear the code style properties for the node and its children.

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
ArgumentTypeDescription
keepBetweenbooleanKeep the raws.between symbols.

Container#clone()

Returns an exact clone of the node.

The resulting cloned node and its (cloned) children will retain code style properties.

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
ArgumentTypeDescription
overridesobjectNew properties to override in the clone.

Returns itself for methods chain.

Container#cloneAfter()

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

ArgumentTypeDescription
overridesobjectNew properties to override in the clone.

Returns itself for methods chain.

Container#cloneBefore()

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

decl.cloneBefore({ prop: '-moz-' + decl.prop })
ArgumentTypeDescription
overridesobjectMew properties to override in the clone.

Returns itself for methods chain.

Container#each()

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
})
ArgumentTypeDescription
callback(node: ChildNode, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Container#error()

Returns a CssSyntaxError instance containing the original position of the node in the source, showing line and column numbers and also a small excerpt to facilitate debugging.

If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).

This method produces very useful error messages.

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
}
ArgumentTypeDescription
messagestringError description.
optionsNodeErrorOptions

Returns CssSyntaxError. Error object to throw it.

Container#every()

Returns true if callback returns true for all of the container’s children.

const noPrefixes = rule.every(i => i.prop[0] !== '-')
ArgumentTypeDescription
condition(node: ChildNode, index: number, nodes: ChildNode[]) => booleanIterator returns true or false.

Returns boolean. Is every child pass condition.

Container#index()

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

rule.index( rule.nodes[2] ) //=> 2
ArgumentTypeDescription
childChildNode | numberChild of the current container.

Returns number. Child index.

Container#insertAfter()

Insert new node after old node within the container.

ArgumentTypeDescription
oldNodeChildNode | numberChild or child’s index.
newNodeChildNode | ChildProps | string | ChildNode[] | ChildProps[] | string[]New node.

Returns itself for methods chain.

Container#insertBefore()

Insert new node before old node within the container.

rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
ArgumentTypeDescription
oldNodeChildNode | numberChild or child’s index.
newNodeChildNode | ChildProps | string | ChildNode[] | ChildProps[] | string[]New node.

Returns itself for methods chain.

Container#next()

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 ChildNode | undefined. Next node.

Container#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position. Symbol position in file.

Container#prepend()

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')
ArgumentTypeDescription
nodes…(Node | Node[] | ChildProps | ChildProps[] | string | string[])[]New nodes.

Returns itself for methods chain.

Container#prev()

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 ChildNode | undefined. Previous node.

Container#push()

Add child to the end of the node.

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

Returns itself for methods chain.

Container#raw()

Returns a Node#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') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string. Code style value.

Container#remove()

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

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

Returns itself for methods chain.

Container#removeAll()

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

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

Returns itself for methods chain.

Container#removeChild()

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
ArgumentTypeDescription
childChildNode | numberChild or child’s index.

Returns itself for methods chain.

Container#replaceValues()

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'
})
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
optionsValueOptions
replacedstring | (substring: string, args: any[]) => string
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
replacedstring | (substring: string, args: any[]) => string

Returns itself for methods chain.

Container#replaceWith()

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

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
ArgumentTypeDescription
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]Mode(s) to replace current one.

Returns itself for methods chain.

Container#root()

Finds the Root instance of the node’s tree.

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

Returns Root. Root parent.

Container#some()

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

const hasPrefix = rule.some(i => i.prop[0] === '-')
ArgumentTypeDescription
condition(node: ChildNode, index: number, nodes: ChildNode[]) => booleanIterator returns true or false.

Returns boolean. Is some child pass condition.

Container#toJSON()

Fix circular links on JSON.stringify().

Returns object. Cleaned object.

Container#toString()

Returns a CSS string representing the node.

new Rule({ selector: 'a' }).toString() //=> "a {}"
ArgumentTypeDescription
stringifierStringifier | SyntaxA syntax to use in string generation.

Returns string. CSS string of this node.

Container#walk()

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.
})
ArgumentTypeDescription
callback(node: ChildNode, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Container#walkAtRules()

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()
  }
})
ArgumentTypeDescription
nameFilterstring | RegExp
callback(atRule: AtRule, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Container#walkComments()

Traverses the container’s descendant nodes, calling callback for each comment node.

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

root.walkComments(comment => {
  comment.remove()
})
ArgumentTypeDescription
callback(comment: Comment, indexed: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Container#walkDecls()

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.

ArgumentTypeDescription
propFilterstring | RegExp
callback(decl: Declaration, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Container#walkRules()

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`)
ArgumentTypeDescription
selectorFilterstring | RegExp
callback(atRule: Rule, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Container#warn()

This method is provided as a convenience wrapper for Result#warn.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property bad')
    }
  }
ArgumentTypeDescription
resultResultThe Result instance that will receive the warning.
textstringWarning message.
optsWarningOptionsWarning Options.

CssSyntaxError

The CSS parser throws this error for broken CSS.

Custom parsers can throw this error for broken custom syntax using the Node#error method.

PostCSS will use the input source map to detect the original error location. If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS, PostCSS will show the original position in the Sass file.

If you need the position in the PostCSS input (e.g., to debug the previous compiler), use error.input.file.

// Raising error from plugin
throw node.error('Unknown variable', { plugin: 'postcss-vars' })
// Catching and checking syntax error
try {
  postcss.parse('a{')
} catch (error) {
  if (error.name === 'CssSyntaxError') {
    error //=> CssSyntaxError
  }
}

CssSyntaxError#column

Source column of the error.

error.column       //=> 1
error.input.column //=> 4

PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use error.input.column.

Type: number.

CssSyntaxError#file

Absolute path to the broken file.

error.file       //=> 'a.sass'
error.input.file //=> 'a.css'

PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use error.input.file.

Type: string.

CssSyntaxError#input

Input object with PostCSS internal information about input file. If input has source map from previous tool, PostCSS will use origin (for example, Sass) source. You can use this object to get PostCSS input source.

error.input.file //=> 'a.css'
error.file       //=> 'a.sass'

Type: FilePosition.

CssSyntaxError#line

Source line of the error.

error.line       //=> 2
error.input.line //=> 4

PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use error.input.line.

Type: number.

CssSyntaxError#message

Full error text in the GNU error format with plugin, file, line and column.

error.message //=> 'a.css:1:1: Unclosed block'

Type: string.

CssSyntaxError#name

Always equal to 'CssSyntaxError'. You should always check error type by error.name === 'CssSyntaxError' instead of error instanceof CssSyntaxError, because npm could have several PostCSS versions.

if (error.name === 'CssSyntaxError') {
  error //=> CssSyntaxError
}

Type: "CssSyntaxError".

CssSyntaxError#plugin

Plugin name, if error came from plugin.

error.plugin //=> 'postcss-vars'

Type: string.

CssSyntaxError#reason

Error message.

error.message //=> 'Unclosed block'

Type: string.

CssSyntaxError#source

Source code of the broken file.

error.source       //=> 'a { b {} }'
error.input.column //=> 'a b { }'

Type: string.

CssSyntaxError#showSourceCode()

Returns a few lines of CSS source that caused the error.

If the CSS has an input source map without sourceContent, this method will return an empty string.

error.showSourceCode() //=> "  4 | }
                       //      5 | a {
                       //    > 6 |   bad
                       //        |   ^
                       //      7 | }
                       //      8 | b {"
ArgumentTypeDescription
colorbooleanWhether arrow will be colored red by terminal color codes. By default, PostCSS will detect color support by process.stdout.isTTY and process.env.NODE_DISABLE_COLORS.

Returns string. Few lines of CSS source that caused the error.

CssSyntaxError#toString()

Returns error position, message and source code of the broken part.

error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block
                 //    > 1 | a {
                 //        | ^"

Returns string. Error position, message and source code.

Declaration

Represents a CSS declaration.

Once (root, { Declaration }) {
  let color = new Declaration({ prop: 'color', value: 'black' })
  root.append(color)
}
const root = postcss.parse('a { color: black }')
const decl = root.first.first
decl.type       //=> 'decl'
decl.toString() //=> ' color: black'

Declaration#important

true if the declaration has an !important annotation.

const root = postcss.parse('a { color: black !important; color: red }')
root.first.first.important //=> true
root.first.last.important  //=> undefined

Type: boolean.

Declaration#parent

The node’s parent node.

root.nodes[0].parent === root

Type: Container | undefined.

Declaration#prop

The declaration's property name.

const root = postcss.parse('a { color: black }')
const decl = root.first.first
decl.prop //=> 'color'

Type: string.

Declaration#raws

Type: DeclarationRaws.

Declaration#source

The input source of the node.

The property is used in source map generation.

If you create a node manually (e.g., with postcss.decl()), that node will not have a source property and will be absent from the source map. For this reason, the plugin developer should consider cloning nodes to create new ones (in which case the new node’s source will reference the original, cloned node) or setting the source property manually.

decl.source.input.from //=> '/home/ai/a.sass'
decl.source.start      //=> { line: 10, column: 2 }
decl.source.end        //=> { line: 10, column: 12 }
// Bad
const prefixed = postcss.decl({
  prop: '-moz-' + decl.prop,
  value: decl.value
})

// Good
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: Source.

Declaration#type

Type: "decl".

Declaration#value

The declaration’s value.

This value will be cleaned of comments. If the source value contained comments, those comments will be available in the raws property. If you have not changed the value, the result of decl.toString() will include the original raws value (comments and all).

const root = postcss.parse('a { color: black }')
const decl = root.first.first
decl.value //=> 'black'

Type: string.

Declaration#variable

true if declaration is declaration of CSS Custom Property or Sass variable.

const root = postcss.parse(':root { --one: 1 }')
let one = root.first.first
one.variable //=> true
const root = postcss.parse('$one: 1')
let one = root.first
one.variable //=> true

Type: boolean.

Declaration#after()

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

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

decl.after('color: black')
ArgumentTypeDescription
newNodeNode | ChildProps | string | Node[]New node.

Returns itself for methods chain.

Declaration#before()

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

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

decl.before('content: ""')
ArgumentTypeDescription
newNodeNode | ChildProps | string | Node[]New node.

Returns itself for methods chain.

Declaration#cleanRaws()

Clear the code style properties for the node and its children.

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
ArgumentTypeDescription
keepBetweenbooleanKeep the raws.between symbols.

Declaration#clone()

ArgumentTypeDescription
overridesPartial<DeclarationProps>New properties to override in the clone.

Returns itself for methods chain.

Declaration#cloneAfter()

ArgumentTypeDescription
overridesPartial<DeclarationProps>New properties to override in the clone.

Returns itself for methods chain.

Declaration#cloneBefore()

ArgumentTypeDescription
overridesPartial<DeclarationProps>Mew properties to override in the clone.

Returns itself for methods chain.

Declaration#error()

Returns a CssSyntaxError instance containing the original position of the node in the source, showing line and column numbers and also a small excerpt to facilitate debugging.

If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).

This method produces very useful error messages.

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
}
ArgumentTypeDescription
messagestringError description.
optionsNodeErrorOptions

Returns CssSyntaxError. Error object to throw it.

Declaration#next()

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 ChildNode | undefined. Next node.

Declaration#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position. Symbol position in file.

Declaration#prev()

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 ChildNode | undefined. Previous node.

Declaration#raw()

Returns a Node#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') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string. Code style value.

Declaration#remove()

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

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

Returns itself for methods chain.

Declaration#replaceWith()

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

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
ArgumentTypeDescription
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]Mode(s) to replace current one.

Returns itself for methods chain.

Declaration#root()

Finds the Root instance of the node’s tree.

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

Returns Root. Root parent.

Declaration#toJSON()

Fix circular links on JSON.stringify().

Returns object. Cleaned object.

Declaration#toString()

Returns a CSS string representing the node.

new Rule({ selector: 'a' }).toString() //=> "a {}"
ArgumentTypeDescription
stringifierStringifier | SyntaxA syntax to use in string generation.

Returns string. CSS string of this node.

Declaration#warn()

This method is provided as a convenience wrapper for Result#warn.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property bad')
    }
  }
ArgumentTypeDescription
resultResultThe Result instance that will receive the warning.
textstringWarning message.
optsWarningOptionsWarning Options.

Input

Represents the source CSS.

const root  = postcss.parse(css, { from: file })
const input = root.source.input

Input#css

Input CSS source.

const input = postcss.parse('a{}', { from: file }).input
input.css //=> "a{}"

Type: string.

Input#file

The absolute path to the CSS source file defined with the from option.

const root = postcss.parse(css, { from: 'a.css' })
root.source.input.file //=> '/home/ai/a.css'

Type: string.

Input#hasBOM

The flag to indicate whether or not the source code has Unicode BOM.

Type: boolean.

Input#id

The unique ID of the CSS source. It will be created if from option is not provided (because PostCSS does not know the file path).

const root = postcss.parse(css)
root.source.input.file //=> undefined
root.source.input.id   //=> "<input css 8LZeVF>"

Type: string.

Input#map

The input source map passed from a compilation step before PostCSS (for example, from Sass compiler).

root.source.input.map.consumer().sources //=> ['a.sass']

Type: PreviousMap.

Input#from

The CSS source identifier. Contains Input#file if the user set the from option, or Input#id if they did not.

const root = postcss.parse(css, { from: 'a.css' })
root.source.input.from //=> "/home/ai/a.css"

const root = postcss.parse(css)
root.source.input.from //=> "<input css 1>"

Input#fromOffset()

Converts source offset to line and column.

ArgumentTypeDescription
offsetnumberSource offset.

Returns { col: number, line: number } | null.

Input#origin()

Reads the input source map and returns a symbol position in the input source (e.g., in a Sass file that was compiled to CSS before being passed to PostCSS).

root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }
ArgumentTypeDescription
linenumberLine in input CSS.
columnnumberColumn in input CSS.

Returns FilePosition | false. Position in input source.

LazyResult

A Promise proxy for the result of PostCSS transformations.

A LazyResult instance is returned by Processor#process.

const lazy = postcss([autoprefixer]).process(css)

LazyResult#catch

Processes input CSS through synchronous and asynchronous plugins and calls onRejected for each error thrown in any plugin.

It implements standard Promise API.

postcss([autoprefixer]).process(css).then(result => {
  console.log(result.css)
}).catch(error => {
  console.error(error)
})

Type: Promise<Result>["catch"].

LazyResult#finally

Processes input CSS through synchronous and asynchronous plugins and calls onFinally on any error or when all plugins will finish work.

It implements standard Promise API.

postcss([autoprefixer]).process(css).finally(() => {
  console.log('processing ended')
})

Type: Promise<Result>["finally"].

LazyResult#then

Processes input CSS through synchronous and asynchronous plugins and calls onFulfilled with a Result instance. If a plugin throws an error, the onRejected callback will be executed.

It implements standard Promise API.

postcss([autoprefixer]).process(css, { from: cssPath }).then(result => {
  console.log(result.css)
})

Type: Promise<Result>["then"].

LazyResult#content

An alias for the css property. Use it with syntaxes that generate non-CSS output.

This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error. This is why this method is only for debug purpose, you should always use LazyResult#then.

LazyResult#css

Processes input CSS through synchronous plugins, converts Root to a CSS string and returns Result#css.

This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error. This is why this method is only for debug purpose, you should always use LazyResult#then.

LazyResult#map

Processes input CSS through synchronous plugins and returns Result#map.

This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error. This is why this method is only for debug purpose, you should always use LazyResult#then.

LazyResult#messages

Processes input CSS through synchronous plugins and returns Result#messages.

This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.

This is why this method is only for debug purpose, you should always use LazyResult#then.

LazyResult#opts

Options from the Processor#process call.

LazyResult#processor

Returns a Processor instance, which will be used for CSS transformations.

LazyResult#root

Processes input CSS through synchronous plugins and returns Result#root.

This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.

This is why this method is only for debug purpose, you should always use LazyResult#then.

LazyResult#async()

Run plugin in async way and return Result.

Returns Promise<Result>. Result with output content.

LazyResult#sync()

Run plugin in sync way and return Result.

Returns Result. Result with output content.

LazyResult#toString()

Alias for the LazyResult#css property.

lazy + '' === lazy.css

Returns string. Output CSS.

LazyResult#warnings()

Processes input CSS through synchronous plugins and calls Result#warnings.

Returns Warning[]. Warnings from plugins.

Node

All node classes inherit the following common methods.

You should not extend this classes to create AST for selector or value parser.

Node#parent

The node’s parent node.

root.nodes[0].parent === root

Type: Container | undefined.

Node#raws

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

Every parser saves its own properties, but the default CSS parser uses:

PostCSS cleans selectors, declaration values and at-rule parameters from comments and extra spaces, but it stores origin content in raws properties. As such, if you don’t change a declaration’s value, PostCSS will use the raw value with comments.

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

Type: any.

Node#source

The input source of the node.

The property is used in source map generation.

If you create a node manually (e.g., with postcss.decl()), that node will not have a source property and will be absent from the source map. For this reason, the plugin developer should consider cloning nodes to create new ones (in which case the new node’s source will reference the original, cloned node) or setting the source property manually.

decl.source.input.from //=> '/home/ai/a.sass'
decl.source.start      //=> { line: 10, column: 2 }
decl.source.end        //=> { line: 10, column: 12 }
// Bad
const prefixed = postcss.decl({
  prop: '-moz-' + decl.prop,
  value: decl.value
})

// Good
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: Source.

Node#type

tring representing the node’s type. Possible values are root, atrule, rule, decl, or comment.

new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'

Type: string.

Node#after()

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

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

decl.after('color: black')
ArgumentTypeDescription
newNodeNode | ChildProps | string | Node[]New node.

Returns itself for methods chain.

Node#before()

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

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

decl.before('content: ""')
ArgumentTypeDescription
newNodeNode | ChildProps | string | Node[]New node.

Returns itself for methods chain.

Node#cleanRaws()

Clear the code style properties for the node and its children.

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
ArgumentTypeDescription
keepBetweenbooleanKeep the raws.between symbols.

Node#clone()

Returns an exact clone of the node.

The resulting cloned node and its (cloned) children will retain code style properties.

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
ArgumentTypeDescription
overridesobjectNew properties to override in the clone.

Returns itself for methods chain.

Node#cloneAfter()

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

ArgumentTypeDescription
overridesobjectNew properties to override in the clone.

Returns itself for methods chain.

Node#cloneBefore()

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

decl.cloneBefore({ prop: '-moz-' + decl.prop })
ArgumentTypeDescription
overridesobjectMew properties to override in the clone.

Returns itself for methods chain.

Node#error()

Returns a CssSyntaxError instance containing the original position of the node in the source, showing line and column numbers and also a small excerpt to facilitate debugging.

If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).

This method produces very useful error messages.

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
}
ArgumentTypeDescription
messagestringError description.
optionsNodeErrorOptions

Returns CssSyntaxError. Error object to throw it.

Node#next()

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 ChildNode | undefined. Next node.

Node#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position. Symbol position in file.

Node#prev()

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 ChildNode | undefined. Previous node.

Node#raw()

Returns a Node#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') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string. Code style value.

Node#remove()

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

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

Returns itself for methods chain.

Node#replaceWith()

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

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
ArgumentTypeDescription
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]Mode(s) to replace current one.

Returns itself for methods chain.

Node#root()

Finds the Root instance of the node’s tree.

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

Returns Root. Root parent.

Node#toJSON()

Fix circular links on JSON.stringify().

Returns object. Cleaned object.

Node#toString()

Returns a CSS string representing the node.

new Rule({ selector: 'a' }).toString() //=> "a {}"
ArgumentTypeDescription
stringifierStringifier | SyntaxA syntax to use in string generation.

Returns string. CSS string of this node.

Node#warn()

This method is provided as a convenience wrapper for Result#warn.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property bad')
    }
  }
ArgumentTypeDescription
resultResultThe Result instance that will receive the warning.
textstringWarning message.
optsWarningOptionsWarning Options.

PreviousMap

Source map information from input CSS. For example, source map after Sass compiler.

This class will automatically find source map in input CSS or in file system near input file (according from option).

const root = parse(css, { from: 'a.sass.css' })
root.input.map //=> PreviousMap

PreviousMap#annotation

sourceMappingURL content.

Type: string.

PreviousMap#file

The CSS source identifier. Contains Input#file if the user set the from option, or Input#id if they did not.

Type: string.

PreviousMap#inline

Was source map inlined by data-uri to input CSS.

Type: boolean.

PreviousMap#mapFile

Path to source map file.

Type: string.

PreviousMap#root

The directory with source map file, if source map is in separated file.

Type: string.

PreviousMap#text

Source map file content.

Type: string.

PreviousMap#consumer()

Create a instance of SourceMapGenerator class from the source-map library to work with source map information.

It is lazy method, so it will create object only on first call and then it will use cache.

Returns SourceMapConsumer. Object with source map information.

PreviousMap#withContent()

Does source map contains sourcesContent with input source text.

Returns boolean. Is sourcesContent present.

Processor

Contains plugins to process CSS. Create one Processor instance, initialize its plugins, and then use that instance on numerous CSS files.

const processor = postcss([autoprefixer, precss])
processor.process(css1).then(result => console.log(result.css))
processor.process(css2).then(result => console.log(result.css))

Processor#plugins

Plugins added to this processor.

const processor = postcss([autoprefixer, precss])
processor.plugins.length //=> 2

Type: (Plugin | Transformer | TransformCallback)[].

Processor#version

Current PostCSS version.

if (result.processor.version.split('.')[0] !== '6') {
  throw new Error('This plugin works only with PostCSS 6')
}

Type: string.

Processor#process()

Parses source CSS and returns a LazyResult Promise proxy. Because some plugins can be asynchronous it doesn’t make any transformations. Transformations will be applied in the LazyResult methods.

processor.process(css, { from: 'a.css', to: 'a.out.css' })
  .then(result => {
     console.log(result.css)
  })
ArgumentTypeDescription
cssstring | { toString: () => string } | Result | LazyResult | RootString with input CSS or any object with a toString() method, like a Buffer. Optionally, senda Result instance and the processor will take the Root from it.
optionsProcessOptions

Returns LazyResult. Promise proxy.

Processor#use()

Adds a plugin to be used as a CSS processor.

PostCSS plugin can be in 4 formats:

Plugins can also be added by passing them as arguments when creating a postcss instance (see [postcss(plugins)]).

Asynchronous plugins should return a Promise instance.

const processor = postcss()
  .use(autoprefixer)
  .use(precss)
ArgumentTypeDescription
pluginAcceptedPluginPostCSS plugin or Processor with plugins.

Returns itself for methods chain.

Result

Provides the result of the PostCSS transformations.

A Result instance is returned by LazyResult#then or Root#toResult methods.

postcss([autoprefixer]).process(css).then(result => {
 console.log(result.css)
})
const result2 = postcss.parse(css).toResult()

Result#css

A CSS string representing of Result#root.

postcss.parse('a{}').toResult().css //=> "a{}"

Type: string.

Result#lastPlugin

Last runned PostCSS plugin.

Type: Plugin | TransformCallback.

Result#map

An instance of SourceMapGenerator class from the source-map library, representing changes to the Result#root instance.

result.map.toJSON() //=> { version: 3, file: 'a.css', … }
if (result.map) {
  fs.writeFileSync(result.opts.to + '.map', result.map.toString())
}

Type: SourceMap.

Result#messages

Contains messages from plugins (e.g., warnings or custom messages). Each message should have type and plugin properties.

AtRule: {
  import: (atRule, { result }) {
    const importedFile = parseImport(atRule)
    result.messages.push({
      type: 'dependency',
      plugin: 'postcss-import',
      file: importedFile,
      parent: result.opts.from
    })
  }
}

Type: Message[].

Result#opts

Options from the Processor#process or Root#toResult call that produced this Result instance.]

root.toResult(opts).opts === opts

Type: ResultOptions.

Result#processor

The Processor instance used for this transformation.

for (const plugin of result.processor.plugins) {
  if (plugin.postcssPlugin === 'postcss-bad') {
    throw 'postcss-good is incompatible with postcss-bad'
  }
})

Type: Processor.

Result#root

Root node after all transformations.

root.toResult().root === root

Type: Root.

Result#content

An alias for the Result#css property. Use it with syntaxes that generate non-CSS output.

result.css === result.content

Result#toString()

Returns for Result#css content.

result + '' === result.css

Returns string. String representing of Result#root.

Result#warn()

Creates an instance of Warning and adds it to Result#messages.

if (decl.important) {
  result.warn('Avoid !important', { node: decl, word: '!important' })
}
ArgumentType
messagestring
optionsWarningOptions

Result#warnings()

Returns warnings from plugins. Filters Warning instances from Result#messages.

result.warnings().forEach(warn => {
  console.warn(warn.toString())
})

Returns Warning[]. Warnings from plugins.

Root

Represents a CSS file and contains all its parsed nodes.

const root = postcss.parse('a{color:black} b{z-index:2}')
root.type         //=> 'root'
root.nodes.length //=> 2

Root#nodes

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'

Type: ChildNode[].

Root#parent

Type: undefined.

Root#raws

Type: RootRaws.

Root#source

The input source of the node.

The property is used in source map generation.

If you create a node manually (e.g., with postcss.decl()), that node will not have a source property and will be absent from the source map. For this reason, the plugin developer should consider cloning nodes to create new ones (in which case the new node’s source will reference the original, cloned node) or setting the source property manually.

decl.source.input.from //=> '/home/ai/a.sass'
decl.source.start      //=> { line: 10, column: 2 }
decl.source.end        //=> { line: 10, column: 12 }
// Bad
const prefixed = postcss.decl({
  prop: '-moz-' + decl.prop,
  value: decl.value
})

// Good
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: Source.

Root#type

Type: "root".

Root#first

The container’s first child.

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

Root#last

The container’s last child.

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

Root#after()

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

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

decl.after('color: black')
ArgumentTypeDescription
newNodeNode | ChildProps | string | Node[]New node.

Returns itself for methods chain.

Root#append()

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')
ArgumentTypeDescription
nodes…(Node | Node[] | ChildProps | ChildProps[] | string | string[])[]New nodes.

Returns itself for methods chain.

Root#before()

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

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

decl.before('content: ""')
ArgumentTypeDescription
newNodeNode | ChildProps | string | Node[]New node.

Returns itself for methods chain.

Root#cleanRaws()

Clear the code style properties for the node and its children.

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
ArgumentTypeDescription
keepBetweenbooleanKeep the raws.between symbols.

Root#clone()

Returns an exact clone of the node.

The resulting cloned node and its (cloned) children will retain code style properties.

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
ArgumentTypeDescription
overridesobjectNew properties to override in the clone.

Returns itself for methods chain.

Root#cloneAfter()

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

ArgumentTypeDescription
overridesobjectNew properties to override in the clone.

Returns itself for methods chain.

Root#cloneBefore()

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

decl.cloneBefore({ prop: '-moz-' + decl.prop })
ArgumentTypeDescription
overridesobjectMew properties to override in the clone.

Returns itself for methods chain.

Root#each()

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
})
ArgumentTypeDescription
callback(node: ChildNode, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Root#error()

Returns a CssSyntaxError instance containing the original position of the node in the source, showing line and column numbers and also a small excerpt to facilitate debugging.

If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).

This method produces very useful error messages.

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
}
ArgumentTypeDescription
messagestringError description.
optionsNodeErrorOptions

Returns CssSyntaxError. Error object to throw it.

Root#every()

Returns true if callback returns true for all of the container’s children.

const noPrefixes = rule.every(i => i.prop[0] !== '-')
ArgumentTypeDescription
condition(node: ChildNode, index: number, nodes: ChildNode[]) => booleanIterator returns true or false.

Returns boolean. Is every child pass condition.

Root#index()

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

rule.index( rule.nodes[2] ) //=> 2
ArgumentTypeDescription
childChildNode | numberChild of the current container.

Returns number. Child index.

Root#insertAfter()

Insert new node after old node within the container.

ArgumentTypeDescription
oldNodeChildNode | numberChild or child’s index.
newNodeChildNode | ChildProps | string | ChildNode[] | ChildProps[] | string[]New node.

Returns itself for methods chain.

Root#insertBefore()

Insert new node before old node within the container.

rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
ArgumentTypeDescription
oldNodeChildNode | numberChild or child’s index.
newNodeChildNode | ChildProps | string | ChildNode[] | ChildProps[] | string[]New node.

Returns itself for methods chain.

Root#next()

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 ChildNode | undefined. Next node.

Root#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position. Symbol position in file.

Root#prepend()

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')
ArgumentTypeDescription
nodes…(Node | Node[] | ChildProps | ChildProps[] | string | string[])[]New nodes.

Returns itself for methods chain.

Root#prev()

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 ChildNode | undefined. Previous node.

Root#push()

Add child to the end of the node.

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

Returns itself for methods chain.

Root#raw()

Returns a Node#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') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string. Code style value.

Root#remove()

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

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

Returns itself for methods chain.

Root#removeAll()

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

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

Returns itself for methods chain.

Root#removeChild()

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
ArgumentTypeDescription
childChildNode | numberChild or child’s index.

Returns itself for methods chain.

Root#replaceValues()

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'
})
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
optionsValueOptions
replacedstring | (substring: string, args: any[]) => string
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
replacedstring | (substring: string, args: any[]) => string

Returns itself for methods chain.

Root#replaceWith()

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

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
ArgumentTypeDescription
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]Mode(s) to replace current one.

Returns itself for methods chain.

Root#root()

Finds the Root instance of the node’s tree.

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

Returns Root. Root parent.

Root#some()

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

const hasPrefix = rule.some(i => i.prop[0] === '-')
ArgumentTypeDescription
condition(node: ChildNode, index: number, nodes: ChildNode[]) => booleanIterator returns true or false.

Returns boolean. Is some child pass condition.

Root#toJSON()

Fix circular links on JSON.stringify().

Returns object. Cleaned object.

Root#toResult()

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 })
ArgumentType
optionsProcessOptions

Returns Result. Result with current root’s CSS.

Root#toString()

Returns a CSS string representing the node.

new Rule({ selector: 'a' }).toString() //=> "a {}"
ArgumentTypeDescription
stringifierStringifier | SyntaxA syntax to use in string generation.

Returns string. CSS string of this node.

Root#walk()

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.
})
ArgumentTypeDescription
callback(node: ChildNode, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Root#walkAtRules()

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()
  }
})
ArgumentTypeDescription
nameFilterstring | RegExp
callback(atRule: AtRule, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Root#walkComments()

Traverses the container’s descendant nodes, calling callback for each comment node.

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

root.walkComments(comment => {
  comment.remove()
})
ArgumentTypeDescription
callback(comment: Comment, indexed: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Root#walkDecls()

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.

ArgumentTypeDescription
propFilterstring | RegExp
callback(decl: Declaration, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Root#walkRules()

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`)
ArgumentTypeDescription
selectorFilterstring | RegExp
callback(atRule: Rule, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Root#warn()

This method is provided as a convenience wrapper for Result#warn.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property bad')
    }
  }
ArgumentTypeDescription
resultResultThe Result instance that will receive the warning.
textstringWarning message.
optsWarningOptionsWarning Options.

Rule

Represents a CSS rule: a selector followed by a declaration block.

Once (root, { Rule }) {
  let a = new Rule({ selector: 'a' })
  a.append(…)
  root.append(a)
}
const root = postcss.parse('a{}')
const rule = root.first
rule.type       //=> 'rule'
rule.toString() //=> 'a{}'

Rule#nodes

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'

Type: ChildNode[].

Rule#parent

The node’s parent node.

root.nodes[0].parent === root

Type: Container | undefined.

Rule#raws

Type: RuleRaws.

Rule#selector

The rule’s full selector represented as a string.

const root = postcss.parse('a, b { }')
const rule = root.first
rule.selector //=> 'a, b'

Type: string.

Rule#selectors

An array containing the rule’s individual selectors. Groups of selectors are split at commas.

const root = postcss.parse('a, b { }')
const rule = root.first

rule.selector  //=> 'a, b'
rule.selectors //=> ['a', 'b']

rule.selectors = ['a', 'strong']
rule.selector //=> 'a, strong'

Type: string[].

Rule#source

The input source of the node.

The property is used in source map generation.

If you create a node manually (e.g., with postcss.decl()), that node will not have a source property and will be absent from the source map. For this reason, the plugin developer should consider cloning nodes to create new ones (in which case the new node’s source will reference the original, cloned node) or setting the source property manually.

decl.source.input.from //=> '/home/ai/a.sass'
decl.source.start      //=> { line: 10, column: 2 }
decl.source.end        //=> { line: 10, column: 12 }
// Bad
const prefixed = postcss.decl({
  prop: '-moz-' + decl.prop,
  value: decl.value
})

// Good
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: Source.

Rule#type

Type: "rule".

Rule#first

The container’s first child.

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

Rule#last

The container’s last child.

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

Rule#after()

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

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

decl.after('color: black')
ArgumentTypeDescription
newNodeNode | ChildProps | string | Node[]New node.

Returns itself for methods chain.

Rule#append()

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')
ArgumentTypeDescription
nodes…(Node | Node[] | ChildProps | ChildProps[] | string | string[])[]New nodes.

Returns itself for methods chain.

Rule#before()

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

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

decl.before('content: ""')
ArgumentTypeDescription
newNodeNode | ChildProps | string | Node[]New node.

Returns itself for methods chain.

Rule#cleanRaws()

Clear the code style properties for the node and its children.

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
ArgumentTypeDescription
keepBetweenbooleanKeep the raws.between symbols.

Rule#clone()

ArgumentTypeDescription
overridesPartial<RuleProps>New properties to override in the clone.

Returns itself for methods chain.

Rule#cloneAfter()

ArgumentTypeDescription
overridesPartial<RuleProps>New properties to override in the clone.

Returns itself for methods chain.

Rule#cloneBefore()

ArgumentTypeDescription
overridesPartial<RuleProps>Mew properties to override in the clone.

Returns itself for methods chain.

Rule#each()

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
})
ArgumentTypeDescription
callback(node: ChildNode, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Rule#error()

Returns a CssSyntaxError instance containing the original position of the node in the source, showing line and column numbers and also a small excerpt to facilitate debugging.

If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).

This method produces very useful error messages.

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
}
ArgumentTypeDescription
messagestringError description.
optionsNodeErrorOptions

Returns CssSyntaxError. Error object to throw it.

Rule#every()

Returns true if callback returns true for all of the container’s children.

const noPrefixes = rule.every(i => i.prop[0] !== '-')
ArgumentTypeDescription
condition(node: ChildNode, index: number, nodes: ChildNode[]) => booleanIterator returns true or false.

Returns boolean. Is every child pass condition.

Rule#index()

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

rule.index( rule.nodes[2] ) //=> 2
ArgumentTypeDescription
childChildNode | numberChild of the current container.

Returns number. Child index.

Rule#insertAfter()

Insert new node after old node within the container.

ArgumentTypeDescription
oldNodeChildNode | numberChild or child’s index.
newNodeChildNode | ChildProps | string | ChildNode[] | ChildProps[] | string[]New node.

Returns itself for methods chain.

Rule#insertBefore()

Insert new node before old node within the container.

rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
ArgumentTypeDescription
oldNodeChildNode | numberChild or child’s index.
newNodeChildNode | ChildProps | string | ChildNode[] | ChildProps[] | string[]New node.

Returns itself for methods chain.

Rule#next()

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 ChildNode | undefined. Next node.

Rule#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position. Symbol position in file.

Rule#prepend()

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')
ArgumentTypeDescription
nodes…(Node | Node[] | ChildProps | ChildProps[] | string | string[])[]New nodes.

Returns itself for methods chain.

Rule#prev()

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 ChildNode | undefined. Previous node.

Rule#push()

Add child to the end of the node.

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

Returns itself for methods chain.

Rule#raw()

Returns a Node#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') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string. Code style value.

Rule#remove()

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

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

Returns itself for methods chain.

Rule#removeAll()

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

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

Returns itself for methods chain.

Rule#removeChild()

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
ArgumentTypeDescription
childChildNode | numberChild or child’s index.

Returns itself for methods chain.

Rule#replaceValues()

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'
})
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
optionsValueOptions
replacedstring | (substring: string, args: any[]) => string
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
replacedstring | (substring: string, args: any[]) => string

Returns itself for methods chain.

Rule#replaceWith()

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

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
ArgumentTypeDescription
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]Mode(s) to replace current one.

Returns itself for methods chain.

Rule#root()

Finds the Root instance of the node’s tree.

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

Returns Root. Root parent.

Rule#some()

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

const hasPrefix = rule.some(i => i.prop[0] === '-')
ArgumentTypeDescription
condition(node: ChildNode, index: number, nodes: ChildNode[]) => booleanIterator returns true or false.

Returns boolean. Is some child pass condition.

Rule#toJSON()

Fix circular links on JSON.stringify().

Returns object. Cleaned object.

Rule#toString()

Returns a CSS string representing the node.

new Rule({ selector: 'a' }).toString() //=> "a {}"
ArgumentTypeDescription
stringifierStringifier | SyntaxA syntax to use in string generation.

Returns string. CSS string of this node.

Rule#walk()

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.
})
ArgumentTypeDescription
callback(node: ChildNode, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Rule#walkAtRules()

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()
  }
})
ArgumentTypeDescription
nameFilterstring | RegExp
callback(atRule: AtRule, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Rule#walkComments()

Traverses the container’s descendant nodes, calling callback for each comment node.

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

root.walkComments(comment => {
  comment.remove()
})
ArgumentTypeDescription
callback(comment: Comment, indexed: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Rule#walkDecls()

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.

ArgumentTypeDescription
propFilterstring | RegExp
callback(decl: Declaration, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Rule#walkRules()

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`)
ArgumentTypeDescription
selectorFilterstring | RegExp
callback(atRule: Rule, index: number) => void | falseIterator receives each node and index.

Returns void | false. Returns false if iteration was broke.

Rule#warn()

This method is provided as a convenience wrapper for Result#warn.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property bad')
    }
  }
ArgumentTypeDescription
resultResultThe Result instance that will receive the warning.
textstringWarning message.
optsWarningOptionsWarning Options.

Warning

Represents a plugin’s warning. It can be created using Node#warn.

if (decl.important) {
  decl.warn(result, 'Avoid !important', { word: '!important' })
}

Warning#column

Column in the input file with this warning’s source.

warning.column //=> 6

Type: number.

Warning#line

Line in the input file with this warning’s source.

warning.line //=> 5

Type: number.

Warning#node

Contains the CSS node that caused the warning.

warning.node.toString() //=> 'color: white !important'

Type: Node.

Warning#plugin

The name of the plugin that created this warning. When you call Node#warn it will fill this property automatically.

warning.plugin //=> 'postcss-important'

Type: string.

Warning#text

The warning message.

warning.text //=> 'Try to avoid !important'

Type: string.

Warning#type

Type to filter warnings from Result#messages. Always equal to "warning".

Type: "warning".

Warning#toString()

Returns a warning position and message.

warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'

Returns string. Warning position and message.

AcceptedPlugin

Type: Plugin | PluginCreator<any> | OldPlugin<any> | TransformCallback | { postcss: TransformCallback | Processor } | Processor.

AnyNode

Type: AtRule | Rule | Declaration | Comment | Root.

AtRuleProcessor

Type: (atRule: AtRule, helper: Helpers) => Promise<void> | void.

AtRuleProps

PropertyType
namestring
nodes(ChildNode | ChildProps)[]
paramsstring | number
rawsAtRuleRaws
sourceSource

AtRuleRaws

PropertyTypeDescription
afterstringThe space symbols after the last child of the node to the end of the node.
afterNamestringThe space between the at-rule name and its parameters.
beforestringThe space symbols before the node. It also stores * and _ symbols before the declaration (IE hack).
betweenstringThe symbols between the last parameter and { for rules.
params{ raw: string, value: string }The rule’s selector with comments.
semicolonbooleanContains true if the last child has an (optional) semicolon.

Builder

ArgumentType
partstring
nodeAnyNode
type"start" | "end"

ChildNode

Type: AtRule | Rule | Declaration | Comment.

ChildProps

Type: AtRuleProps | RuleProps | DeclarationProps | CommentProps.

CommentProcessor

Type: (comment: Comment, helper: Helpers) => Promise<void> | void.

CommentProps

PropertyType
rawsCommentRaws
sourceSource
textstring

CommentRaws

PropertyTypeDescription
beforestringThe space symbols before the node.
leftstringThe space symbols between /* and the comment’s text.
rightbooleanThe space symbols between the comment’s text.

ContainerProps

PropertyType
nodes(ChildNode | ChildProps)[]
sourceSource

DeclarationProcessor

Type: (decl: Declaration, helper: Helpers) => Promise<void> | void.

DeclarationProps

PropertyType
propstring
rawsDeclarationRaws
valuestring

DeclarationRaws

PropertyTypeDescription
beforestringThe space symbols before the node. It also stores * and _ symbols before the declaration (IE hack).
betweenstringThe symbols between the property and value for declarations.
importantstringThe content of the important statement, if it is not just !important.
value{ raw: string, value: string }Declaration value with comments.

FilePosition

PropertyTypeDescription
columnnumberColumn in source file.
filestringAbsolute path to the source file.
linenumberLine in source file.
sourcestringSource code.
urlstringURL for the source file.

Helpers

Type: object & Postcss.

Message

PropertyTypeDescription
pluginstringSource PostCSS plugin name.
typestringMessage type.

NodeErrorOptions

PropertyTypeDescription
indexnumberAn index inside a node's string that should be highlighted as source of error.
pluginstringPlugin name that created this error. PostCSS will set it automatically.
wordstringA word inside a node's string, that should be highlighted as source of error.

NodeProps

PropertyType
sourceSource

OldPlugin

ArgumentType
optsT
ArgumentType
rootRoot
resultResult

Returns Transformer.

OldPlugin#postcss

Type: Transformer.

OldPlugin#postcssPlugin

Type: string.

OldPlugin#postcssVersion

Type: string.

Parser

ArgumentType
cssstring | { toString: () => string }
optsPick<ProcessOptions, "map" | "from">

Returns Root.

Plugin

Plugin#AtRule

Will be called on allAtRule nodes.

Will be called again on node or children changes.

Type: AtRuleProcessor | { [name: string]: AtRuleProcessor}.

Plugin#AtRuleExit

Will be called on all AtRule nodes, when all children will be processed.

Will be called again on node or children changes.

Type: AtRuleProcessor | { [name: string]: AtRuleProcessor}.

Plugin#Comment

Will be called on all Comment nodes.

Will be called again on node or children changes.

Type: CommentProcessor.

Plugin#CommentExit

Will be called on all Comment nodes after listeners for Comment event.

Will be called again on node or children changes.

Type: CommentProcessor.

Plugin#Declaration

Will be called on all Declaration nodes after listeners for Declaration event.

Will be called again on node or children changes.

Type: DeclarationProcessor | { [prop: string]: DeclarationProcessor}.

Plugin#DeclarationExit

Will be called on all Declaration nodes.

Will be called again on node or children changes.

Type: DeclarationProcessor | { [prop: string]: DeclarationProcessor}.

Plugin#Exit

Will be called when all other listeners processed the document.

This listener will not be called again.

Type: RootProcessor.

Plugin#Once

Will be called on Root node once.

Type: RootProcessor.

Plugin#OnceExit

Will be called on Root node once, when all children will be processed.

Type: RootProcessor.

Plugin#Root

Will be called on Root node.

Will be called again on children changes.

Type: RootProcessor.

Plugin#RootExit

Will be called on Root node, when all children will be processed.

Will be called again on children changes.

Type: RootProcessor.

Plugin#Rule

Will be called on all Rule nodes.

Will be called again on node or children changes.

Type: RuleProcessor.

Plugin#RuleExit

Will be called on all Rule nodes, when all children will be processed.

Will be called again on node or children changes.

Type: RuleProcessor.

Plugin#postcssPlugin

Type: string.

Plugin#prepare

Type: (result: Result) => Processors.

PluginCreator

ArgumentType
optsPluginOptions

Returns Plugin.

PluginCreator#postcss

Type: true.

Position

PropertyTypeDescription
columnnumberSource line in file.
linenumberSource column in file.
offsetnumberSource offset in file.

ProcessOptions

PropertyTypeDescription
fromstringThe path of the CSS source file. You should always set from, because it is used in source map generation and syntax error messages.
mapSourceMapOptions | booleanSource map options
parserSyntax | ParserFunction to generate AST by string.
stringifierSyntax | StringifierClass to generate string by AST.
syntaxSyntaxObject with parse and stringify.
tostringThe path where you'll put the output CSS file. You should always set to to generate correct source maps.

Processors

Processors#AtRule

Will be called on allAtRule nodes.

Will be called again on node or children changes.

Type: AtRuleProcessor | { [name: string]: AtRuleProcessor}.

Processors#AtRuleExit

Will be called on all AtRule nodes, when all children will be processed.

Will be called again on node or children changes.

Type: AtRuleProcessor | { [name: string]: AtRuleProcessor}.

Processors#Comment

Will be called on all Comment nodes.

Will be called again on node or children changes.

Type: CommentProcessor.

Processors#CommentExit

Will be called on all Comment nodes after listeners for Comment event.

Will be called again on node or children changes.

Type: CommentProcessor.

Processors#Declaration

Will be called on all Declaration nodes after listeners for Declaration event.

Will be called again on node or children changes.

Type: DeclarationProcessor | { [prop: string]: DeclarationProcessor}.

Processors#DeclarationExit

Will be called on all Declaration nodes.

Will be called again on node or children changes.

Type: DeclarationProcessor | { [prop: string]: DeclarationProcessor}.

Processors#Exit

Will be called when all other listeners processed the document.

This listener will not be called again.

Type: RootProcessor.

Processors#Once

Will be called on Root node once.

Type: RootProcessor.

Processors#OnceExit

Will be called on Root node once, when all children will be processed.

Type: RootProcessor.

Processors#Root

Will be called on Root node.

Will be called again on children changes.

Type: RootProcessor.

Processors#RootExit

Will be called on Root node, when all children will be processed.

Will be called again on children changes.

Type: RootProcessor.

Processors#Rule

Will be called on all Rule nodes.

Will be called again on node or children changes.

Type: RuleProcessor.

Processors#RuleExit

Will be called on all Rule nodes, when all children will be processed.

Will be called again on node or children changes.

Type: RuleProcessor.

ResultOptions

PropertyTypeDescription
fromstringThe path of the CSS source file. You should always set from, because it is used in source map generation and syntax error messages.
mapSourceMapOptions | booleanSource map options
nodeNodeThe CSS node that was the source of the warning.
parserSyntax | ParserFunction to generate AST by string.
pluginstringName of plugin that created this warning. Result#warn will fill it automatically with Plugin#postcssPlugin value.
stringifierSyntax | StringifierClass to generate string by AST.
syntaxSyntaxObject with parse and stringify.
tostringThe path where you'll put the output CSS file. You should always set to to generate correct source maps.

RootProcessor

Type: (root: Root, helper: Helpers) => Promise<void> | void.

RootProps

PropertyType
nodes(ChildNode | ChildProps)[]
rawsRootRaws
sourceSource

RootRaws

PropertyTypeDescription
afterstringThe space symbols after the last child to the end of file.
semicolonbooleanIs the last child has an (optional) semicolon.

RuleProcessor

Type: (rule: Rule, helper: Helpers) => Promise<void> | void.

RuleProps

PropertyType
nodes(ChildNode | ChildProps)[]
rawsRuleRaws
selectorstring
selectorsstring[]
sourceSource

RuleRaws

PropertyTypeDescription
afterstringThe space symbols after the last child of the node to the end of the node.
beforestringThe space symbols before the node. It also stores * and _ symbols before the declaration (IE hack).
betweenstringThe symbols between the selector and { for rules.
ownSemicolonstringContains true if there is semicolon after rule.
selector{ raw: string, value: string }The rule’s selector with comments.
semicolonbooleanContains true if the last child has an (optional) semicolon.

Source

PropertyTypeDescription
endPositionThe ending position of the node's source.
inputInputThe file source of the node.
startPositionThe starting position of the node’s source.

SourceMap

Type: SourceMapGenerator & object.

SourceMapOptions

PropertyTypeDescription
absolutebooleanUse absolute path in generated source map.
annotationstring | boolean | (file: string, root: Root) => stringIndicates that PostCSS should add annotation comments to the CSS. By default, PostCSS will always add a comment with a path to the source map. PostCSS will not add annotations to CSS files that do not contain any comments. By default, PostCSS presumes that you want to save the source map as opts.to + '.map' and will use this path in the annotation comment. A different path can be set by providing a string value for annotation. If you have set inline: true, annotation cannot be disabled.
fromstringOverride from in map’s sources.
inlinebooleanIndicates that the source map should be embedded in the output CSS as a Base64-encoded comment. By default, it is true. But if all previous maps are external, not inline, PostCSS will not embed the map even if you do not set this option. If you have an inline source map, the result.map property will be empty, as the source map will be contained within the text of result.css.
prevstring | boolean | object | (file: string) => stringSource map content from a previous processing step (e.g., Sass). PostCSS will try to read the previous source map automatically (based on comments within the source CSS), but you can use this option to identify it manually. If desired, you can omit the previous map with prev: false.
sourcesContentbooleanIndicates that PostCSS should set the origin content (e.g., Sass source) of the source map. By default, it is true. But if all previous maps do not contain sources content, PostCSS will also leave it out even if you do not set this option.

Stringifier

ArgumentType
nodeAnyNode
builderBuilder

Syntax

PropertyTypeDescription
parseParserFunction to generate AST by string.
stringifyStringifierClass to generate string by AST.

TransformCallback

ArgumentType
rootRoot
resultResult

Returns Promise<void> | void.

Transformer

ArgumentType
rootRoot
resultResult

Returns Promise<void> | void.

Transformer#postcssPlugin

Type: string.

Transformer#postcssVersion

Type: string.

ValueOptions

PropertyTypeDescription
faststringString that’s used to narrow down values and speed up the regexp search.
propsstring[]An array of property names.

WarningOptions

PropertyTypeDescription
indexnumberIndex in CSS node string that caused the warning.
nodeNodeCSS node that caused the warning.
pluginstringName of the plugin that created this warning. Result#warn fills this property automatically.
wordstringWord in CSS source that caused the warning.

list

list.comma

Safely splits comma-separated values (such as those for transition-* and background properties).

Once (root, { list }) {
  list.comma('black, linear-gradient(white, black)')
  //=> ['black', 'linear-gradient(white, black)']
}
ArgumentTypeDescription
strstringComma-separated values.

Returns string[]. Split values.

list.space

Safely splits space-separated values (such as those for background, border-radius, and other shorthand properties).

Once (root, { list }) {
  list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
}
ArgumentTypeDescription
strstringSpace-separated values.

Returns string[]. Split values.