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 default. Processor to process multiple CSS.

postcss.AtRule

Type: typeof default.

postcss.Comment

Type: typeof default.

postcss.Container

Type: typeof default.

postcss.CssSyntaxError

Type: typeof default.

postcss.Declaration

Type: typeof default.

postcss.Input

Type: typeof default.

postcss.Node

Type: typeof default.

postcss.Result

Type: typeof default.

postcss.Root

Type: typeof default.

postcss.Rule

Type: typeof default.

postcss.Warning

Type: typeof default.

postcss.fromJSON

Rehydrate a JSON AST (from Node#toJSON) back into the AST classes.

const json = root.toJSON()
// save to file, send by network, etc
const root2  = postcss.fromJSON(json)

Type: JSONHydrator.

postcss.list

Contains the list module.

Type: List.

postcss.parse

Parses source css and returns a new Root or Document 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<default>.

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 default. New at-rule node.

postcss.comment()

Creates a new Comment node.

ArgumentTypeDescription
defaultsCommentPropsProperties for the new node.

Returns default. New comment node

postcss.decl()

Creates a new Declaration node.

ArgumentTypeDescription
defaultsDeclarationPropsProperties for the new node.

Returns default. New declaration node.

postcss.document()

Creates a new Document node.

ArgumentTypeDescription
defaultsDocumentPropsProperties for the new node.

Returns default. New document node.

postcss.root()

Creates a new Root node.

ArgumentTypeDescription
defaultsRootPropsProperties for the new node.

Returns default. New root node.

postcss.rule()

Creates a new Rule node.

ArgumentType
defaultsRuleProps

Returns default. 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: default<ChildNode>.

AtRule#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: 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

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

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

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
newNodestring | ChildProps | default | default[]New node.

Returns default. This node 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…(string | ChildProps | default | default[] | ChildProps[] | string[])[]New nodes.

Returns default. This node for methods chain.

AtRule#assign()

Assigns properties to the current node.

decl.assign({ prop: 'word-wrap', value: 'break-word' })
ArgumentTypeDescription
overridesobject | AtRulePropsNew properties to override the node.

Returns default. Current node to 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
newNodestring | ChildProps | default | default[]New node.

Returns default. This node 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()

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
overridesPartial<AtRuleProps>New properties to override in the clone.

Returns default. Clone of the node.

AtRule#cloneAfter()

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

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

Returns default. New node.

AtRule#cloneBefore()

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

decl.cloneBefore({ prop: '-moz-' + decl.prop })
ArgumentTypeDescription
overridesPartial<AtRuleProps>Mew properties to override in the clone.

Returns default. New node

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) => false | voidIterator 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 default. 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
childnumber | ChildNodeChild of the current container.

Returns number. Child index.

AtRule#insertAfter()

Insert new node after old node within the container.

ArgumentTypeDescription
oldNodenumber | ChildNodeChild or child’s index.
newNodestring | ChildNode | ChildProps | ChildNode[] | ChildProps[] | string[]New node.

Returns default. This node for methods chain.

AtRule#insertBefore()

Insert new node before old node within the container.

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

Returns default. This node 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()
  }
}
ArgumentType

Returns ChildNode. Next node.

AtRule#positionBy()

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

ArgumentTypeDescription
optsPick<WarningOptions, "word" | "index">Options.

Returns Position. Position.

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

Returns default. This node 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)
}
ArgumentType

Returns ChildNode. Previous node.

AtRule#push()

Add child to the end of the node.

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

Returns default. This node for methods chain.

AtRule#rangeBy()

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

ArgumentTypeDescription
optsPick<WarningOptions, "word" | "index" | "endIndex">Options.

Returns Range. Range.

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

Returns default. Node to make calls chain.

AtRule#removeAll()

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

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

Returns default. This node 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
childnumber | ChildNodeChild or child’s index.

Returns default. This node 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 default. This node 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 default. Current node to methods chain.

AtRule#root()

Finds the Root instance of the node’s tree.

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

Returns default. 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().

ArgumentType

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) => false | voidIterator 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: default, index: number) => false | voidIterator 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: default, indexed: number) => false | voidIterator 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: default, index: number) => false | voidIterator 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(rule: default, index: number) => false | voidIterator 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
resultdefaultThe Result instance that will receive the warning.
textstringWarning message.
optsWarningOptionsWarning Options.

Returns default. Created warning object.

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: default<ChildNode>.

Comment#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: 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

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

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

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
newNodestring | ChildProps | default | default[]New node.

Returns default. This node for methods chain.

Comment#assign()

Assigns properties to the current node.

decl.assign({ prop: 'word-wrap', value: 'break-word' })
ArgumentTypeDescription
overridesobject | CommentPropsNew properties to override the node.

Returns default.

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
newNodestring | ChildProps | default | default[]New node.

Returns default. This node 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()

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
overridesPartial<CommentProps>New properties to override in the clone.

Returns default.

Comment#cloneAfter()

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

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

Returns default.

Comment#cloneBefore()

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

decl.cloneBefore({ prop: '-moz-' + decl.prop })
ArgumentTypeDescription
overridesPartial<CommentProps>Mew properties to override in the clone.

Returns default.

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 default. 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()
  }
}
ArgumentType

Returns ChildNode. Next node.

Comment#positionBy()

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

ArgumentTypeDescription
optsPick<WarningOptions, "word" | "index">Options.

Returns Position. Position.

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

Returns ChildNode. Previous node.

Comment#rangeBy()

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

ArgumentTypeDescription
optsPick<WarningOptions, "word" | "index" | "endIndex">Options.

Returns Range. Range.

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

Returns default. Node to make calls 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 default. Current node to methods chain.

Comment#root()

Finds the Root instance of the node’s tree.

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

Returns default. Root parent.

Comment#toJSON()

Fix circular links on JSON.stringify().

ArgumentType

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
resultdefaultThe Result instance that will receive the warning.
textstringWarning message.
optsWarningOptionsWarning Options.

Returns default. Created warning object.

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: Child[].

Container#parent

The node’s parent node.

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

Type: default<ChildNode> | default.

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
newNodestring | ChildProps | default | default[]New node.

Returns default<Child>. This node 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…(string | ChildProps | default | default[] | ChildProps[] | string[])[]New nodes.

Returns default<Child>. This node for methods chain.

Container#assign()

Assigns properties to the current node.

decl.assign({ prop: 'word-wrap', value: 'break-word' })
ArgumentTypeDescription
overridesobjectNew properties to override the node.

Returns default<Child>. Current node to 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
newNodestring | ChildProps | default | default[]New node.

Returns default<Child>. This node 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 default<Child>. Clone of the node.

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 default<Child>. New node.

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 default<Child>. New node

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: Child, index: number) => false | voidIterator 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 default. 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: Child, index: number, nodes: Child[]) => 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
childnumber | ChildChild of the current container.

Returns number. Child index.

Container#insertAfter()

Insert new node after old node within the container.

ArgumentTypeDescription
oldNodenumber | ChildChild or child’s index.
newNodestring | ChildProps | Child | Child[] | ChildProps[] | string[]New node.

Returns default<Child>. This node for methods chain.

Container#insertBefore()

Insert new node before old node within the container.

rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
ArgumentTypeDescription
oldNodenumber | ChildChild or child’s index.
newNodestring | ChildProps | Child | Child[] | ChildProps[] | string[]New node.

Returns default<Child>. This node 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()
  }
}
ArgumentType

Returns ChildNode. Next node.

Container#positionBy()

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

ArgumentTypeDescription
optsPick<WarningOptions, "word" | "index">Options.

Returns Position. Position.

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

Returns default<Child>. This node 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)
}
ArgumentType

Returns ChildNode. Previous node.

Container#push()

Add child to the end of the node.

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

Returns default<Child>. This node for methods chain.

Container#rangeBy()

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

ArgumentTypeDescription
optsPick<WarningOptions, "word" | "index" | "endIndex">Options.

Returns Range. Range.

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

Returns default<Child>. Node to make calls chain.

Container#removeAll()

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

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

Returns default<Child>. This node 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
childnumber | ChildChild or child’s index.

Returns default<Child>. This node 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 default<Child>. This node 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 default<Child>. Current node to methods chain.

Container#root()

Finds the Root instance of the node’s tree.

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

Returns default. 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: Child, index: number, nodes: Child[]) => booleanIterator returns true or false.

Returns boolean. Is some child pass condition.

Container#toJSON()

Fix circular links on JSON.stringify().

ArgumentType

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) => false | voidIterator 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: default, index: number) => false | voidIterator 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: default, indexed: number) => false | voidIterator 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: default, index: number) => false | voidIterator 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(rule: default, index: number) => false | voidIterator 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
resultdefaultThe Result instance that will receive the warning.
textstringWarning message.
optsWarningOptionsWarning Options.

Returns default. Created warning object.

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#endColumn

Source column of the error's end, exclusive. Provided if the error pertains to a range.

error.endColumn       //=> 1
error.input.endColumn //=> 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.endColumn.

Type: number.

CssSyntaxError#endLine

Source line of the error's end, exclusive. Provided if the error pertains to a range.

error.endLine       //=> 3
error.input.endLine //=> 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.endLine.

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.source //=> 'a b { }'

Type: string.

CssSyntaxError#stack

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 {
                 //        | ^"
ArgumentType

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: default<ChildNode>.

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

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: 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

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

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

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
newNodestring | ChildProps | default | default[]New node.

Returns default. This node for methods chain.

Declaration#assign()

Assigns properties to the current node.

decl.assign({ prop: 'word-wrap', value: 'break-word' })
ArgumentTypeDescription
overridesobject | DeclarationPropsNew properties to override the node.

Returns default.

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
newNodestring | ChildProps | default | default[]New node.

Returns default. This node 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()

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
overridesPartial<DeclarationProps>New properties to override in the clone.

Returns default.

Declaration#cloneAfter()

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

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

Returns default.

Declaration#cloneBefore()

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

decl.cloneBefore({ prop: '-moz-' + decl.prop })
ArgumentTypeDescription
overridesPartial<DeclarationProps>Mew properties to override in the clone.

Returns default.

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 default. 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()
  }
}
ArgumentType

Returns ChildNode. Next node.

Declaration#positionBy()

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

ArgumentTypeDescription
optsPick<WarningOptions, "word" | "index">Options.

Returns Position. Position.

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

Returns ChildNode. Previous node.

Declaration#rangeBy()

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

ArgumentTypeDescription
optsPick<WarningOptions, "word" | "index" | "endIndex">Options.

Returns Range. Range.

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

Returns default. Node to make calls 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 default. Current node to methods chain.

Declaration#root()

Finds the Root instance of the node’s tree.

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

Returns default. Root parent.

Declaration#toJSON()

Fix circular links on JSON.stringify().

ArgumentType

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
resultdefaultThe Result instance that will receive the warning.
textstringWarning message.
optsWarningOptionsWarning Options.

Returns default. Created warning object.

Document

Represents a file and contains all its parsed nodes.

Experimental: some aspects of this node could change within minor or patch version releases.

const document = htmlParser(
  '<html><style>a{color:black}</style><style>b{z-index:2}</style>'
)
document.type         //=> 'document'
document.nodes.length //=> 2

Document#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: default[].

Document#parent

The node’s parent node.

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

Type: undefined.

Document#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.

Document#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.

Document#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: "document".

Document#first

The container’s first child.

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

Document#last

The container’s last child.

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

Document#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
newNodestring | ChildProps | default | default[]New node.

Returns default. This node for methods chain.

Document#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…(string | ChildProps | default | default[] | ChildProps[] | string[])[]New nodes.

Returns default. This node for methods chain.

Document#assign()

Assigns properties to the current node.

decl.assign({ prop: 'word-wrap', value: 'break-word' })
ArgumentTypeDescription
overridesobjectNew properties to override the node.

Returns default. Current node to methods chain.

Document#before()

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

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

decl.before('content: ""')
ArgumentTypeDescription
newNodestring | ChildProps | default | default[]New node.

Returns default. This node for methods chain.

Document#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.

Document#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 default. Clone of the node.

Document#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 default. New node.

Document#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 default. New node

Document#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: default, index: number) => false | voidIterator receives each node and index.

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

Document#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 default. Error object to throw it.

Document#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: default, index: number, nodes: default[]) => booleanIterator returns true or false.

Returns boolean. Is every child pass condition.

Document#index()

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

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

Returns number. Child index.

Document#insertAfter()

Insert new node after old node within the container.

ArgumentTypeDescription
oldNodenumber | defaultChild or child’s index.
newNodestring | ChildProps | ChildProps[] | string[] | default | default[]New node.

Returns default. This node for methods chain.

Document#insertBefore()

Insert new node before old node within the container.

rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
ArgumentTypeDescription
oldNodenumber | defaultChild or child’s index.
newNodestring | ChildProps | ChildProps[] | string[] | default | default[]New node.

Returns default. This node for methods chain.

Document#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()
  }
}
ArgumentType

Returns ChildNode. Next node.

Document#positionBy()

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

ArgumentTypeDescription
optsPick<WarningOptions, "word" | "index">Options.

Returns Position. Position.

Document#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position. Symbol position in file.

Document#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…(string | ChildProps | default | default[] | ChildProps[] | string[])[]New nodes.

Returns default. This node for methods chain.

Document#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)
}
ArgumentType

Returns ChildNode. Previous node.

Document#push()

Add child to the end of the node.

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

Returns default. This node for methods chain.

Document#rangeBy()

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

ArgumentTypeDescription
optsPick<WarningOptions, "word" | "index" | "endIndex">Options.

Returns Range. Range.

Document#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.

Document#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()
}
ArgumentType

Returns default. Node to make calls chain.

Document#removeAll()

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

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

Returns default. This node for methods chain.

Document#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
childnumber | defaultChild or child’s index.

Returns default. This node for methods chain.

Document#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 default. This node for methods chain.

Document#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 default. Current node to methods chain.

Document#root()

Finds the Root instance of the node’s tree.

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

Returns default. Root parent.

Document#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: default, index: number, nodes: default[]) => booleanIterator returns true or false.

Returns boolean. Is some child pass condition.

Document#toJSON()

Fix circular links on JSON.stringify().

ArgumentType

Returns object. Cleaned object.

Document#toResult()

Returns a Result instance representing the document’s CSS roots.

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

Returns default. Result with current document’s CSS.

Document#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.

Document#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) => false | voidIterator receives each node and index.

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

Document#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: default, index: number) => false | voidIterator receives each node and index.

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

Document#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: default, indexed: number) => false | voidIterator receives each node and index.

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

Document#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: default, index: number) => false | voidIterator receives each node and index.

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

Document#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(rule: default, index: number) => false | voidIterator receives each node and index.

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

Document#warn()

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

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

Returns default. Created warning object.

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: default.

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 }.

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). Optionally takes an end position, exclusive.

root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }
root.source.input.origin(1, 1, 1, 4)
//=> { file: 'a.css', line: 3, column: 1, endLine: 3, endColumn: 4 }
ArgumentTypeDescription
linenumberLine for inclusive start position in input CSS.
columnnumberColumn for inclusive start position in input CSS.
endLinenumberLine for exclusive end position in input CSS.
endColumnnumberColumn for exclusive end position in input CSS.

Returns false | FilePosition. 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: (onrejected: (reason: any) => TResult | PromiseLike<TResult>) => Promise<default | TResult>.

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: (onfinally: () => void) => Promise<default>.

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: (onfulfilled: (value: default) => TResult1 | PromiseLike<TResult1>, onrejected: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<TResult1 | TResult2>.

LazyResult#[toStringTag]

Returns the default string description of an object. Required to implement the Promise interface.

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.

PostCSS runners 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.

PostCSS runners 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.

PostCSS runners 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.

PostCSS runners 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.

PostCSS runners should always use LazyResult#then.

LazyResult#async()

Run plugin in async way and return Result.

ArgumentType

Returns Promise<default>. Result with output content.

LazyResult#sync()

Run plugin in sync way and return Result.

ArgumentType

Returns default. Result with output content.

LazyResult#toString()

Alias for the LazyResult#css property.

lazy + '' === lazy.css
ArgumentType

Returns string. Output CSS.

LazyResult#warnings()

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

ArgumentType

Returns default[]. Warnings from plugins.

NoWorkResult

A Promise proxy for the result of PostCSS transformations. This lazy result instance doesn't parse css unless NoWorkResult#root or Result#root are accessed. See the example below for details. A NoWork instance is returned by Processor#process ONLY when no plugins defined.

const noWorkResult = postcss().process(css) // No plugins are defined.
                                            // CSS is not parsed
let root = noWorkResult.root // now css is parsed because we accessed the root

NoWorkResult#catch

Type: (onrejected: (reason: any) => TResult | PromiseLike<TResult>) => Promise<default | TResult>.

NoWorkResult#finally

Type: (onfinally: () => void) => Promise<default>.

NoWorkResult#then

Type: (onfulfilled: (value: default) => TResult1 | PromiseLike<TResult1>, onrejected: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<TResult1 | TResult2>.

NoWorkResult#[toStringTag]

NoWorkResult#content

NoWorkResult#css

NoWorkResult#map

NoWorkResult#messages

NoWorkResult#opts

NoWorkResult#processor

NoWorkResult#root

NoWorkResult#async()

ArgumentType

Returns Promise<default>.

NoWorkResult#sync()

ArgumentType

Returns default.

NoWorkResult#toString()

ArgumentType

Returns string.

NoWorkResult#warnings()

ArgumentType

Returns default[].

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: default<ChildNode> | default.

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
newNodestring | ChildProps | default | default[]New node.

Returns default. This node for methods chain.

Node#assign()

Assigns properties to the current node.

decl.assign({ prop: 'word-wrap', value: 'break-word' })
ArgumentTypeDescription
overridesobjectNew properties to override the node.

Returns default. Current node to 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
newNodestring | ChildProps | default | default[]New node.

Returns default. This node 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 default. Clone of the node.

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 default. New node.

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 default. New node

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 default. 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()
  }
}
ArgumentType

Returns ChildNode. Next node.

Node#positionBy()

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

ArgumentTypeDescription
optsPick<WarningOptions, "word" | "index">Options.

Returns Position. Position.

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

Returns ChildNode. Previous node.

Node#rangeBy()

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

ArgumentTypeDescription
optsPick<WarningOptions, "word" | "index" | "endIndex">Options.

Returns Range. Range.

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

Returns default. Node to make calls 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 default. Current node to methods chain.

Node#root()

Finds the Root instance of the node’s tree.

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

Returns default. Root parent.

Node#toJSON()

Fix circular links on JSON.stringify().

ArgumentType

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
resultdefaultThe Result instance that will receive the warning.
textstringWarning message.
optsWarningOptionsWarning Options.

Returns default. Created warning object.

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.

ArgumentType

Returns SourceMapConsumer. Object with source map information.

PreviousMap#withContent()

Does source map contains sourcesContent with input source text.

ArgumentType

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, postcssNested])
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, postcssNested])
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 | default | default | default | { toString: () => string }String 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 default | default. 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(postcssNested)
ArgumentTypeDescription
pluginAcceptedPluginPostCSS plugin or Processor with plugins.

Returns default. Current processor to make 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: default.

Result#root

Root node after all transformations.

root.toResult().root === root

Type: default | default.

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
ArgumentType

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

Returns default. Created warning.

Result#warnings()

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

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

Returns default[]. 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

The node’s parent node.

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

Type: default.

Root#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: 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

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

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

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
newNodestring | ChildProps | default | default[]New node.

Returns default. This node 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…(string | ChildProps | default | default[] | ChildProps[] | string[])[]New nodes.

Returns default. This node for methods chain.

Root#assign()

Assigns properties to the current node.

decl.assign({ prop: 'word-wrap', value: 'break-word' })
ArgumentTypeDescription
overridesobject | RootPropsNew properties to override the node.

Returns default. Current node to 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
newNodestring | ChildProps | default | default[]New node.

Returns default. This node 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 default. Clone of the node.

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 default. New node.

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 default. New node

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) => false | voidIterator 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 default. 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
childnumber | ChildNodeChild of the current container.

Returns number. Child index.

Root#insertAfter()

Insert new node after old node within the container.

ArgumentTypeDescription
oldNodenumber | ChildNodeChild or child’s index.
newNodestring | ChildNode | ChildProps | ChildNode[] | ChildProps[] | string[]New node.

Returns default. This node for methods chain.

Root#insertBefore()

Insert new node before old node within the container.

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

Returns default. This node 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()
  }
}
ArgumentType

Returns ChildNode. Next node.

Root#positionBy()

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

ArgumentTypeDescription
optsPick<WarningOptions, "word" | "index">Options.

Returns Position. Position.

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

Returns default. This node 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)
}
ArgumentType

Returns ChildNode. Previous node.

Root#push()

Add child to the end of the node.

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

Returns default. This node for methods chain.

Root#rangeBy()

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

ArgumentTypeDescription
optsPick<WarningOptions, "word" | "index" | "endIndex">Options.

Returns Range. Range.

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

Returns default. Node to make calls chain.

Root#removeAll()

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

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

Returns default. This node 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
childnumber | ChildNodeChild or child’s index.

Returns default. This node 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 default. This node 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 default. Current node to methods chain.

Root#root()

Finds the Root instance of the node’s tree.

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

Returns default. 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().

ArgumentType

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 default. 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) => false | voidIterator 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: default, index: number) => false | voidIterator 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: default, indexed: number) => false | voidIterator 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: default, index: number) => false | voidIterator 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(rule: default, index: number) => false | voidIterator 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
resultdefaultThe Result instance that will receive the warning.
textstringWarning message.
optsWarningOptionsWarning Options.

Returns default. Created warning object.

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: default<ChildNode>.

Rule#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: 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

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

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

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
newNodestring | ChildProps | default | default[]New node.

Returns default. This node 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…(string | ChildProps | default | default[] | ChildProps[] | string[])[]New nodes.

Returns default. This node for methods chain.

Rule#assign()

Assigns properties to the current node.

decl.assign({ prop: 'word-wrap', value: 'break-word' })
ArgumentTypeDescription
overridesobject | RulePropsNew properties to override the node.

Returns default. Current node to 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
newNodestring | ChildProps | default | default[]New node.

Returns default. This node 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()

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
overridesPartial<RuleProps>New properties to override in the clone.

Returns default. Clone of the node.

Rule#cloneAfter()

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

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

Returns default. New node.

Rule#cloneBefore()

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

decl.cloneBefore({ prop: '-moz-' + decl.prop })
ArgumentTypeDescription
overridesPartial<RuleProps>Mew properties to override in the clone.

Returns default. New node

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) => false | voidIterator 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 default. 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
childnumber | ChildNodeChild of the current container.

Returns number. Child index.

Rule#insertAfter()

Insert new node after old node within the container.

ArgumentTypeDescription
oldNodenumber | ChildNodeChild or child’s index.
newNodestring | ChildNode | ChildProps | ChildNode[] | ChildProps[] | string[]New node.

Returns default. This node for methods chain.

Rule#insertBefore()

Insert new node before old node within the container.

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

Returns default. This node 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()
  }
}
ArgumentType

Returns ChildNode. Next node.

Rule#positionBy()

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

ArgumentTypeDescription
optsPick<WarningOptions, "word" | "index">Options.

Returns Position. Position.

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

Returns default. This node 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)
}
ArgumentType

Returns ChildNode. Previous node.

Rule#push()

Add child to the end of the node.

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

Returns default. This node for methods chain.

Rule#rangeBy()

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

ArgumentTypeDescription
optsPick<WarningOptions, "word" | "index" | "endIndex">Options.

Returns Range. Range.

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

Returns default. Node to make calls chain.

Rule#removeAll()

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

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

Returns default. This node 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
childnumber | ChildNodeChild or child’s index.

Returns default. This node 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 default. This node 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 default. Current node to methods chain.

Rule#root()

Finds the Root instance of the node’s tree.

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

Returns default. 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().

ArgumentType

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) => false | voidIterator 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: default, index: number) => false | voidIterator 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: default, indexed: number) => false | voidIterator 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: default, index: number) => false | voidIterator 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(rule: default, index: number) => false | voidIterator 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
resultdefaultThe Result instance that will receive the warning.
textstringWarning message.
optsWarningOptionsWarning Options.

Returns default. Created warning object.

Stringifier

Stringifier#builder

Type: Builder.

Stringifier#atrule()

ArgumentType
nodedefault
semicolonboolean

Stringifier#beforeAfter()

ArgumentType
nodeAnyNode
detect"before" | "after"

Returns string.

Stringifier#block()

ArgumentType
nodeAnyNode
startstring

Stringifier#body()

ArgumentType
nodedefault<ChildNode>

Stringifier#comment()

ArgumentType
nodedefault

Stringifier#decl()

ArgumentType
nodedefault
semicolonboolean

Stringifier#document()

ArgumentType
nodedefault

Stringifier#raw()

ArgumentType
nodeAnyNode
ownstring
detectstring

Returns string.

Stringifier#rawBeforeClose()

ArgumentType
rootdefault

Returns string.

Stringifier#rawBeforeComment()

ArgumentType
rootdefault
nodedefault

Returns string.

Stringifier#rawBeforeDecl()

ArgumentType
rootdefault
nodedefault

Returns string.

Stringifier#rawBeforeOpen()

ArgumentType
rootdefault

Returns string.

Stringifier#rawBeforeRule()

ArgumentType
rootdefault

Returns string.

Stringifier#rawColon()

ArgumentType
rootdefault

Returns string.

Stringifier#rawEmptyBody()

ArgumentType
rootdefault

Returns string.

Stringifier#rawIndent()

ArgumentType
rootdefault

Returns string.

Stringifier#rawSemicolon()

ArgumentType
rootdefault

Returns boolean.

Stringifier#rawValue()

ArgumentType
nodeAnyNode
propstring

Returns string.

Stringifier#root()

ArgumentType
nodedefault

Stringifier#rule()

ArgumentType
nodedefault

Stringifier#stringify()

ArgumentType
nodeAnyNode
semicolonboolean

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 for inclusive start position in the input file with this warning’s source.

warning.column //=> 6

Type: number.

Warning#endColumn

Column for exclusive end position in the input file with this warning’s source.

warning.endColumn //=> 4

Type: number.

Warning#endLine

Line for exclusive end position in the input file with this warning’s source.

warning.endLine //=> 6

Type: number.

Warning#line

Line for inclusive start position 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: default.

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'
ArgumentType

Returns string. Warning position and message.

AcceptedPlugin

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

AnyNode

Type: default | default | default | default | default | default.

AnyNode

AtRule

AtRuleProps

PropertyTypeDescription
namestringName of the at-rule.
nodes(ChildNode | ChildProps)[]
paramsstring | numberParameters following the name of the at-rule.
rawsAtRuleRawsInformation used to generate byte-to-byte equal node string as it was in the origin input.
sourceSource

AtRuleProps

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: default.

ChildNode

Type: default | default | default | default.

ChildNode

ChildProps

Type: RootProps.

ChildProps

Type: AtRuleProps | RuleProps | DeclarationProps | CommentProps.

ChildProps

Comment

CommentProps

PropertyTypeDescription
rawsCommentRawsInformation used to generate byte-to-byte equal node string as it was in the origin input.
sourceSource
textstringContent of the comment.

CommentProps

CommentRaws

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

Container

ContainerProps

PropertyType
nodes(ChildNode | ChildProps)[]
sourceSource

ContainerProps

CssSyntaxError

Declaration

DeclarationProps

PropertyTypeDescription
importantbooleanWhether the declaration has an !important annotation.
propstringName of the declaration.
rawsDeclarationRawsInformation used to generate byte-to-byte equal node string as it was in the origin input.
valuestringValue of the declaration.

DeclarationProps

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.

Document

DocumentProps

PropertyTypeDescription
nodesdefault[]
rawsRecord<string, any>Information to generate byte-to-byte equal node string as it was in the origin input. Every parser saves its own properties.
sourceSource

DocumentProps

FilePosition

PropertyTypeDescription
columnnumberColumn of inclusive start position in source file.
endColumnnumberColumn of exclusive end position in source file.
endLinenumberLine of exclusive end position in source file.
filestringAbsolute path to the source file.
linenumberLine of inclusive start position in source file.
sourcestringSource code.
urlstringURL for the source file.

FilePosition

Helpers

Type: object & Postcss.

Input

JSONHydrator

ArgumentType
dataobject[]
ArgumentType
dataobject

Returns default[].

LazyResult

Message

Message

PropertyTypeDescription
pluginstringSource PostCSS plugin name.
typestringMessage type.

Node

NodeErrorOptions

PropertyTypeDescription
endIndexnumberAn ending index inside a node's string that should be highlighted as source of error.
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.

NodeErrorOptions

NodeProps

PropertyType
sourceSource

NodeProps

OldPlugin

ArgumentType
optsT
ArgumentType
rootdefault
resultdefault

Returns Transformer.

OldPlugin#postcss

Type: Transformer.

OldPlugin#postcssPlugin

Type: string.

OldPlugin#postcssVersion

Type: string.

Parser

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

Returns RootNode.

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#Document

Will be called on Document node.

Will be called again on children changes.

Type: DocumentProcessor.

Plugin#DocumentExit

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

Will be called again on children changes.

Type: DocumentProcessor.

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()

ArgumentType
resultdefault

Returns Processors.

PluginCreator

ArgumentType
optsPluginOptions

Returns default | Plugin.

PluginCreator#postcss

Type: true.

Position

PropertyTypeDescription
columnnumberSource line in file. In contrast to offset it starts from 1.
linenumberSource column in file.
offsetnumberSource offset in file. It starts from 0.

Position

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.
mapboolean | SourceMapOptionsSource map options
parserSyntax | Parser<default | default>Function to generate AST by string.
stringifierStringifier | SyntaxClass 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.

Processor

Range

Range#end

End position, exclusive.

Type: Position.

Range#start

Start position, inclusive.

Type: Position.

RangePosition

A position that is part of a range.

PropertyTypeDescription
columnnumberThe column number in the input.
linenumberThe line number in the input.

Result

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.
mapboolean | SourceMapOptionsSource map options
nodedefaultThe CSS node that was the source of the warning.
parserSyntax | Parser<default | default>Function to generate AST by string.
pluginstringName of plugin that created this warning. Result#warn will fill it automatically with Plugin#postcssPlugin value.
stringifierStringifier | SyntaxClass 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.

Root

RootProps

RootProps

PropertyTypeDescription
nodes(ChildNode | ChildProps)[]
rawsRootRawsInformation used to generate byte-to-byte equal node string as it was in the origin input.
sourceSource

RootRaws

PropertyTypeDescription
afterstringThe space symbols after the last child to the end of file.
codeAfterstringNon-CSS code after Root, when Root is inside Document. Experimental: some aspects of this node could change within minor or patch version releases.
codeBeforestringNon-CSS code before Root, when Root is inside Document. Experimental: some aspects of this node could change within minor or patch version releases.
semicolonbooleanIs the last child has an (optional) semicolon.

Rule

RuleProps

RuleProps

PropertyTypeDescription
nodes(ChildNode | ChildProps)[]
rawsRuleRawsInformation used to generate byte-to-byte equal node string as it was in the origin input.
selectorstringSelector or selectors of the rule.
selectorsstring[]Selectors of the rule represented as an array of strings.
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 inclusive ending position of the node's source.
inputdefaultThe file source of the node.
startPositionThe inclusive starting position of the node’s source.

Source

SourceMap

Type: SourceMapGenerator & object.

SourceMapOptions

PropertyTypeDescription
absolutebooleanUse absolute path in generated source map.
annotationstring | boolean | (file: string, root: default) => 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
parseParser<default | default>Function to generate AST by string.
stringifyStringifierClass to generate string by AST.

TransformCallback

ArgumentType
rootdefault
resultdefault

Returns void | Promise<void>.

Transformer

ArgumentType
rootdefault
resultdefault

Returns void | Promise<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.

Warning

WarningOptions

WarningOptions

PropertyTypeDescription
endRangePositionEnd position, exclusive, in CSS node string that caused the warning.
endIndexnumberEnd index, exclusive, in CSS node string that caused the warning.
indexnumberStart index, inclusive, in CSS node string that caused the warning.
nodedefaultCSS node that caused the warning.
pluginstringName of the plugin that created this warning. Result#warn fills this property automatically.
startRangePositionStart position, inclusive, in CSS node string that caused the warning.
wordstringWord in CSS source that caused the warning.

comment

ArgumentType
defaultsCommentProps

Returns default.

fromJSON

ArgumentType
dataobject[]
ArgumentType
dataobject

Returns default[].

fromJSON

ArgumentType
dataobject[]
ArgumentType
dataobject

Returns default[].

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.

list.split()

Safely splits values.

Once (root, { list }) {
  list.split('1px calc(10% + 1px)', [' ', '\n', '\t']) //=> ['1px', 'calc(10% + 1px)']
}
ArgumentTypeDescription
stringstringseparated values.
separatorsstring[]array of separators.
lastbooleanboolean indicator.

Returns string[]. Split values.

parse

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

Returns default | default.

stringify

ArgumentType
nodeAnyNode
builderBuilder