postcss

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

let postcss = require('postcss')

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

Returns Processor.

postcss.AcceptedPlugin

Type: Object | OldPlugin<any> | Plugin | PluginCreator<any> | Processor | TransformCallback.

postcss.Builder

ArgumentType
partstring
nodeAnyNode
type"end" | "start"

postcss.Helpers

Type: Object & Postcss.

postcss.JSONHydrator

ArgumentType
dataobject
ArgumentType
dataobject[]

Returns Node.

postcss.OldPlugin

ArgumentType
optsT
ArgumentType
rootRoot
resultResult<Document_ | Root>

Returns Transformer.

postcss.Parser

ArgumentType
cssstring | Object
optsPick<ProcessOptions<Document_ | Root>, "map" | "from">

Returns RootNode.

postcss.PluginCreator

ArgumentType
optsPluginOptions

Returns Processor | Plugin.

postcss.Postcss

Type: typeof postcss.

postcss.SourceMap

Type: SourceMapGenerator & Object.

postcss.Stringifier

ArgumentType
nodeAnyNode
builderBuilder

postcss.TransformCallback

ArgumentType
rootRoot
resultResult<Document_ | Root>

Returns void | Promise<void>.

postcss.Transformer

ArgumentType
rootRoot
resultResult<Document_ | Root>

Returns void | Promise<void>.

postcss.atRule

Creates a new AtRule node.

ArgumentTypeDescription
defaultsAtRulePropsProperties for the new node.

Returns AtRule_.

postcss.comment

Creates a new Comment node.

ArgumentTypeDescription
defaultsCommentPropsProperties for the new node.

Returns Comment_.

postcss.decl

Creates a new Declaration node.

ArgumentTypeDescription
defaultsDeclarationPropsProperties for the new node.

Returns Declaration_.

postcss.document

Creates a new Document node.

ArgumentTypeDescription
defaultsDocumentPropsProperties for the new node.

Returns Document_.

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)
ArgumentType
dataobject
ArgumentType
dataobject[]

Returns Node.

postcss.list

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
ArgumentType
cssstring | Object
optsPick<ProcessOptions<Document_ | Root>, "map" | "from">

Returns Root.

postcss.root

Creates a new Root node.

ArgumentTypeDescription
defaultsRootPropsProperties for the new node.

Returns Root.

postcss.rule

Creates a new Rule node.

ArgumentType
defaultsRuleProps

Returns Rule.

postcss.stringify

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

ArgumentType
nodeAnyNode
builderBuilder

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#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 | Node | ChildProps | Node[]New node.

Returns AtRule.

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

Returns AtRule.

AtRule#assign()

It assigns properties to an existing node instance.

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

Returns AtRule.

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

Returns AtRule.

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

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

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

Returns AtRule.

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

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

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
callbackFunctionIterator receives each node and index.

Returns void | false.

AtRule#error()

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

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

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

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

This method returns the error instance instead of throwing it.

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

Returns CssSyntaxError_.

AtRule#every()

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

const noPrefixes = rule.every(i => i.prop[0] !== '-')
ArgumentTypeDescription
conditionFunctionIterator returns true or false.

Returns boolean.

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.

AtRule#insertAfter()

Insert new node after old node within the container.

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

Returns AtRule.

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 | string[] | ChildNode | ChildNode[] | ChildProps | ChildProps[]New node.

Returns AtRule.

AtRule#name

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

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

Type: string.

AtRule#next()

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

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

Returns ChildNode.

AtRule#nodes

An array containing the layer’s children.

const root = postcss.parse('@layer example { a { color: black } }')
const layer = root.first
layer.nodes.length           //=> 1
layer.nodes[0].selector      //=> 'a'

Can be undefinded if the at-rule has no body.

const root = postcss.parse('@layer a, b, c;')
const layer = root.first
layer.nodes //=> undefined

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

It represents parent of the current node.

root.nodes[0].parent === root //=> true

Type: ContainerWithChildren<ChildNode>.

AtRule#positionBy()

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

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

Returns Position.

AtRule#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position.

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

Returns AtRule.

AtRule#prev()

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

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

Returns ChildNode.

AtRule#push()

Add child to the end of the node.

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

Returns AtRule.

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, "index" | "word" | "endIndex">Options.

Returns Range.

AtRule#raw()

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

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string.

AtRule#raws

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

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

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

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

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

Type: AtRuleRaws.

AtRule#remove()

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

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

Returns AtRule.

AtRule#removeAll()

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

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

Returns AtRule.

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

AtRule#replaceValues()

ArgumentType
patternstring | RegExp
replacedstring | Function
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
optionsValueOptions
replacedstring | Function

Returns AtRule.

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 | ChildNode[] | ChildProps | ChildProps[])[]Mode(s) to replace current one.

Returns AtRule.

AtRule#root()

Finds the Root instance of the node’s tree.

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

Returns Root.

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
conditionFunctionIterator returns true or false.

Returns boolean.

AtRule#source

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

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

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

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

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

 atrule.parent.insertBefore(atrule, rule)
}

Type: Source.

AtRule#toJSON()

Fix circular links on JSON.stringify().

Returns object.

AtRule#toString()

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

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

Returns string.

AtRule#type

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

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

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

declaration.type //=> 'decl'

Type: "atrule".

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

AtRule#walkComments()

ArgumentType
callbackFunction

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

AtRule#warn()

It is a wrapper for Result#warn, providing convenient way of generating warnings.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
ArgumentTypeDescription
resultResult<Document_ | Root>The Result instance that will receive the warning.
messagestringDescription for the warning.
optionsWarningOptionsOptions for the warning.

Returns Warning.

Comment

It represents a class that handles CSS comments

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

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

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

Returns Comment.

Comment#assign()

It assigns properties to an existing node instance.

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

Returns Comment.

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

Returns Comment.

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

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

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

Returns Comment.

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

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

Comment#error()

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

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

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

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

This method returns the error instance instead of throwing it.

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

Returns CssSyntaxError_.

Comment#next()

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

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

Returns ChildNode.

Comment#parent

It represents parent of the current node.

root.nodes[0].parent === root //=> true

Type: Container_<ChildNode>.

Comment#positionBy()

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

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

Returns Position.

Comment#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position.

Comment#prev()

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

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

Returns ChildNode.

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, "index" | "word" | "endIndex">Options.

Returns Range.

Comment#raw()

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

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string.

Comment#raws

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

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

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

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

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

Type: CommentRaws.

Comment#remove()

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

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

Returns Comment.

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 | ChildNode[] | ChildProps | ChildProps[])[]Mode(s) to replace current one.

Returns Comment.

Comment#root()

Finds the Root instance of the node’s tree.

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

Returns Root.

Comment#source

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

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

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

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

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

 atrule.parent.insertBefore(atrule, rule)
}

Type: Source.

Comment#text

The comment's text.

Type: string.

Comment#toJSON()

Fix circular links on JSON.stringify().

Returns object.

Comment#toString()

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

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

Returns string.

Comment#type

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

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

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

declaration.type //=> 'decl'

Type: "comment".

Comment#warn()

It is a wrapper for Result#warn, providing convenient way of generating warnings.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
ArgumentTypeDescription
resultResult<Document_ | Root>The Result instance that will receive the warning.
messagestringDescription for the warning.
optionsWarningOptionsOptions for the warning.

Returns Warning.

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#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 | Node | ChildProps | Node[]New node.

Returns Container<Child>.

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

Returns Container<Child>.

Container#assign()

It assigns properties to an existing node instance.

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

Returns Container<Child>.

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

Returns Container<Child>.

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

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

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

Returns Container<Child>.

Container#cloneAfter()

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

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

Returns Container<Child>.

Container#cloneBefore()

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

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

Returns Container<Child>.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Container#error()

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

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

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

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

This method returns the error instance instead of throwing it.

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

Returns CssSyntaxError_.

Container#every()

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

const noPrefixes = rule.every(i => i.prop[0] !== '-')
ArgumentTypeDescription
conditionFunctionIterator returns true or false.

Returns boolean.

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.

Container#insertAfter()

Insert new node after old node within the container.

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

Returns Container<Child>.

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 | string[] | Child | ChildProps | ChildProps[] | Child[]New node.

Returns Container<Child>.

Container#next()

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

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

Returns ChildNode.

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

It represents parent of the current node.

root.nodes[0].parent === root //=> true

Type: Container_<ChildNode> | Document_.

Container#positionBy()

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

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

Returns Position.

Container#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position.

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

Returns Container<Child>.

Container#prev()

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

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

Returns ChildNode.

Container#push()

Add child to the end of the node.

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

Returns Container<Child>.

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, "index" | "word" | "endIndex">Options.

Returns Range.

Container#raw()

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

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string.

Container#raws

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

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

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

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

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

Type: any.

Container#remove()

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

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

Returns Container<Child>.

Container#removeAll()

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

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

Returns Container<Child>.

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 Container<Child>.

Container#replaceValues()

ArgumentType
patternstring | RegExp
replacedstring | Function
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
optionsValueOptions
replacedstring | Function

Returns Container<Child>.

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 | ChildNode[] | ChildProps | ChildProps[])[]Mode(s) to replace current one.

Returns Container<Child>.

Container#root()

Finds the Root instance of the node’s tree.

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

Returns Root.

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
conditionFunctionIterator returns true or false.

Returns boolean.

Container#source

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

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

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

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

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

 atrule.parent.insertBefore(atrule, rule)
}

Type: Source.

Container#toJSON()

Fix circular links on JSON.stringify().

Returns object.

Container#toString()

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

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

Returns string.

Container#type

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

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

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

declaration.type //=> 'decl'

Type: string.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Container#walkComments()

ArgumentType
callbackFunction

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Container#warn()

It is a wrapper for Result#warn, providing convenient way of generating warnings.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
ArgumentTypeDescription
resultResult<Document_ | Root>The Result instance that will receive the warning.
messagestringDescription for the warning.
optionsWarningOptionsOptions for the warning.

Returns Warning.

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

CssSyntaxError#source

Source code of the broken file.

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

Type: string.

CssSyntaxError#stack

Type: string.

CssSyntaxError#toString()

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

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

Returns string.

Declaration

It represents a class that handles CSS declarations

Once (root, { Declaration }) {
  const 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#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 | Node | ChildProps | Node[]New node.

Returns Declaration.

Declaration#assign()

It assigns properties to an existing node instance.

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

Returns Declaration.

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

Returns Declaration.

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

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

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

Returns Declaration.

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

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

Declaration#error()

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

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

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

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

This method returns the error instance instead of throwing it.

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

Returns CssSyntaxError_.

Declaration#important

It represents a specificity of the declaration.

If true, the CSS declaration will have an important specifier.

const root = postcss.parse('a { color: black !important; color: red }')

root.first.first.important //=> true
root.first.last.important  //=> undefined

Type: boolean.

Declaration#next()

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

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

Returns ChildNode.

Declaration#parent

It represents parent of the current node.

root.nodes[0].parent === root //=> true

Type: ContainerWithChildren<ChildNode>.

Declaration#positionBy()

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

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

Returns Position.

Declaration#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position.

Declaration#prev()

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

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

Returns ChildNode.

Declaration#prop

The property name for a CSS declaration.

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

decl.prop //=> 'color'

Type: string.

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, "index" | "word" | "endIndex">Options.

Returns Range.

Declaration#raw()

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

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string.

Declaration#raws

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

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

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

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

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

Type: DeclarationRaws.

Declaration#remove()

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

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

Returns Declaration.

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 | ChildNode[] | ChildProps | ChildProps[])[]Mode(s) to replace current one.

Returns Declaration.

Declaration#root()

Finds the Root instance of the node’s tree.

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

Returns Root.

Declaration#source

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

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

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

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

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

 atrule.parent.insertBefore(atrule, rule)
}

Type: Source.

Declaration#toJSON()

Fix circular links on JSON.stringify().

Returns object.

Declaration#toString()

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

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

Returns string.

Declaration#type

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

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

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

declaration.type //=> 'decl'

Type: "decl".

Declaration#value

The property value for a CSS declaration.

Any CSS comments inside the value string will be filtered out. CSS comments present in the source value will be available in the raws property.

Assigning new value would ignore the comments in raws property while compiling node to string.

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

decl.value //=> 'black'

Type: string.

Declaration#variable

It represents a getter that returns true if a declaration starts with -- or $, which are used to declare variables in CSS and SASS/SCSS.

const root = postcss.parse(':root { --one: 1 }')
const one = root.first.first

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

one.variable //=> true

Type: boolean.

Declaration#warn()

It is a wrapper for Result#warn, providing convenient way of generating warnings.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
ArgumentTypeDescription
resultResult<Document_ | Root>The Result instance that will receive the warning.
messagestringDescription for the warning.
optionsWarningOptionsOptions for the warning.

Returns Warning.

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#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 | Node | ChildProps | Node[]New node.

Returns Document.

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

Returns Document.

Document#assign()

It assigns properties to an existing node instance.

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

Returns Document.

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

Returns Document.

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

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

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

Returns Document.

Document#cloneAfter()

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

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

Returns Document.

Document#cloneBefore()

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

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

Returns Document.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Document#error()

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

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

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

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

This method returns the error instance instead of throwing it.

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

Returns CssSyntaxError_.

Document#every()

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

const noPrefixes = rule.every(i => i.prop[0] !== '-')
ArgumentTypeDescription
conditionFunctionIterator returns true or false.

Returns boolean.

Document#index()

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

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

Returns number.

Document#insertAfter()

Insert new node after old node within the container.

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

Returns Document.

Document#insertBefore()

Insert new node before old node within the container.

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

Returns Document.

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

Returns ChildNode.

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

Document#parent

It represents parent of the current node.

root.nodes[0].parent === root //=> true

Type: undefined.

Document#positionBy()

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

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

Returns Position.

Document#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position.

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

Returns Document.

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

Returns ChildNode.

Document#push()

Add child to the end of the node.

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

Returns Document.

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, "index" | "word" | "endIndex">Options.

Returns Range.

Document#raw()

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

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string.

Document#raws

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

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

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

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

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

Type: any.

Document#remove()

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

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

Returns Document.

Document#removeAll()

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

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

Returns Document.

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 | RootChild or child’s index.

Returns Document.

Document#replaceValues()

ArgumentType
patternstring | RegExp
replacedstring | Function
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
optionsValueOptions
replacedstring | Function

Returns Document.

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 | ChildNode[] | ChildProps | ChildProps[])[]Mode(s) to replace current one.

Returns Document.

Document#root()

Finds the Root instance of the node’s tree.

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

Returns Root.

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
conditionFunctionIterator returns true or false.

Returns boolean.

Document#source

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

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

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

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

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

 atrule.parent.insertBefore(atrule, rule)
}

Type: Source.

Document#toJSON()

Fix circular links on JSON.stringify().

Returns 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<Document_ | Root>

Returns Result<Document_ | Root>.

Document#toString()

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

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

Returns string.

Document#type

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

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

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

declaration.type //=> 'decl'

Type: "document".

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Document#walkComments()

ArgumentType
callbackFunction

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Document#warn()

It is a wrapper for Result#warn, providing convenient way of generating warnings.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
ArgumentTypeDescription
resultResult<Document_ | Root>The Result instance that will receive the warning.
messagestringDescription for the warning.
optionsWarningOptionsOptions for the warning.

Returns Warning.

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

ArgumentType
messagestring
startObject | Object
endObject | Object
optsObject
ArgumentType
messagestring
linenumber
columnnumber
optsObject
ArgumentType
messagestring
offsetnumber
optsObject

Returns CssSyntaxError_.

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

Converts source offset to line and column.

ArgumentTypeDescription
offsetnumberSource offset.

Returns Object.

Input#hasBOM

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

Type: boolean.

Input#id

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

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

Type: string.

Input#map

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

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

Type: PreviousMap_.

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

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

Run plugin in async way and return Result.

Returns Promise<Result<RootNode>>.

LazyResult#catch

Type: Function.

LazyResult#finally

Type: Function.

LazyResult#sync()

Run plugin in sync way and return Result.

Returns Result<RootNode>.

LazyResult#then

Type: Function.

LazyResult#toString()

Alias for the LazyResult#css property.

lazy + '' === lazy.css

Returns string.

LazyResult#warnings()

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

Returns Warning[].

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

Run plugin in async way and return Result.

Returns Promise<Result<Root>>.

NoWorkResult#catch

Type: Function.

NoWorkResult#finally

Type: Function.

NoWorkResult#sync()

Run plugin in sync way and return Result.

Returns Result<Root>.

NoWorkResult#then

Type: Function.

NoWorkResult#toString()

Alias for the LazyResult#css property.

lazy + '' === lazy.css

Returns string.

NoWorkResult#warnings()

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

Returns Warning[].

Node

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

Returns Node.

Node#assign()

It assigns properties to an existing node instance.

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

Returns Node.

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

Returns Node.

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

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

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

Returns 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 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 Node.

Node#error()

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

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

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

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

This method returns the error instance instead of throwing it.

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

Returns CssSyntaxError_.

Node#next()

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

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

Returns ChildNode.

Node#parent

It represents parent of the current node.

root.nodes[0].parent === root //=> true

Type: Container_<ChildNode> | Document_.

Node#positionBy()

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

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

Returns Position.

Node#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position.

Node#prev()

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

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

Returns ChildNode.

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, "index" | "word" | "endIndex">Options.

Returns Range.

Node#raw()

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

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string.

Node#raws

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

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

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

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

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

Type: any.

Node#remove()

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

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

Returns Node.

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 | ChildNode[] | ChildProps | ChildProps[])[]Mode(s) to replace current one.

Returns Node.

Node#root()

Finds the Root instance of the node’s tree.

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

Returns Root.

Node#source

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

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

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

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

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

 atrule.parent.insertBefore(atrule, rule)
}

Type: Source.

Node#toJSON()

Fix circular links on JSON.stringify().

Returns object.

Node#toString()

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

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

Returns string.

Node#type

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

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

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

declaration.type //=> 'decl'

Type: string.

Node#warn()

It is a wrapper for Result#warn, providing convenient way of generating warnings.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
ArgumentTypeDescription
resultResult<Document_ | Root>The Result instance that will receive the warning.
messagestringDescription for the warning.
optionsWarningOptionsOptions for the warning.

Returns Warning.

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

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

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

Returns SourceMapConsumer.

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

Does source map contains sourcesContent with input source text.

Returns boolean.

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 | TransformCallback | Transformer)[].

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 | Root | Result<Document_ | Root> | Object | LazyResult_<Document_ | Root>String with input CSS or any object with a toString() method, like a Buffer. Optionally, send a Result instance and the processor will take the Root from it.
ArgumentTypeDescription
cssstring | Root | Result<Document_ | Root> | LazyResult_<Document_ | Root> | ObjectString with input CSS or any object with a toString() method, like a Buffer. Optionally, send a Result instance and the processor will take the Root from it.
optionsProcessOptions<RootNode>

Returns NoWorkResult_ | LazyResult_<Document_ | Root>.

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

Processor#version

Current PostCSS version.

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

Type: string.

Result

Provides the result of the PostCSS transformations.

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

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

Result#css

A CSS string representing of Result#root.

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

Type: string.

Result#lastPlugin

Last runned PostCSS plugin.

Type: Plugin | TransformCallback.

Result#map

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

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

Type: SourceMap.

Result#messages

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

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

Type: Message[].

Result#opts

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

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

Type: ResultOptions.

Result#processor

The Processor instance used for this transformation.

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

Type: Processor.

Result#root

Root node after all transformations.

root.toResult().root === root

Type: RootNode.

Result#toString()

Returns for Result#css content.

result + '' === result.css

Returns string.

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

Result#warnings()

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

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

Returns Warning[].

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#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 | Node | ChildProps | Node[]New node.

Returns Root.

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

Returns Root.

Root#assign()

It assigns properties to an existing node instance.

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

Returns Root.

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

Returns Root.

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

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

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

Returns Root.

Root#cloneAfter()

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

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

Returns Root.

Root#cloneBefore()

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

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

Returns Root.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Root#error()

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

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

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

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

This method returns the error instance instead of throwing it.

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

Returns CssSyntaxError_.

Root#every()

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

const noPrefixes = rule.every(i => i.prop[0] !== '-')
ArgumentTypeDescription
conditionFunctionIterator returns true or false.

Returns boolean.

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.

Root#insertAfter()

Insert new node after old node within the container.

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

Returns Root.

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 | string[] | ChildNode | ChildNode[] | ChildProps | ChildProps[]New node.

Returns Root.

Root#next()

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

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

Returns ChildNode.

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

It represents parent of the current node.

root.nodes[0].parent === root //=> true

Type: Document_.

Root#positionBy()

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

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

Returns Position.

Root#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position.

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

Returns Root.

Root#prev()

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

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

Returns ChildNode.

Root#push()

Add child to the end of the node.

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

Returns Root.

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, "index" | "word" | "endIndex">Options.

Returns Range.

Root#raw()

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

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string.

Root#raws

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

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

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

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

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

Type: RootRaws.

Root#remove()

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

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

Returns Root.

Root#removeAll()

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

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

Returns Root.

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

Root#replaceValues()

ArgumentType
patternstring | RegExp
replacedstring | Function
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
optionsValueOptions
replacedstring | Function

Returns Root.

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 | ChildNode[] | ChildProps | ChildProps[])[]Mode(s) to replace current one.

Returns Root.

Root#root()

Finds the Root instance of the node’s tree.

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

Returns Root.

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
conditionFunctionIterator returns true or false.

Returns boolean.

Root#source

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

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

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

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

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

 atrule.parent.insertBefore(atrule, rule)
}

Type: Source.

Root#toJSON()

Fix circular links on JSON.stringify().

Returns 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<Document_ | Root>

Returns Result<Document_ | Root>.

Root#toString()

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

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

Returns string.

Root#type

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

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

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

declaration.type //=> 'decl'

Type: "root".

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Root#walkComments()

ArgumentType
callbackFunction

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Root#warn()

It is a wrapper for Result#warn, providing convenient way of generating warnings.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
ArgumentTypeDescription
resultResult<Document_ | Root>The Result instance that will receive the warning.
messagestringDescription for the warning.
optionsWarningOptionsOptions for the warning.

Returns Warning.

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#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 | Node | ChildProps | Node[]New node.

Returns Rule.

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

Returns Rule.

Rule#assign()

It assigns properties to an existing node instance.

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

Returns Rule.

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

Returns Rule.

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

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

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

Returns Rule.

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

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

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Rule#error()

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

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

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

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

This method returns the error instance instead of throwing it.

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

Returns CssSyntaxError_.

Rule#every()

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

const noPrefixes = rule.every(i => i.prop[0] !== '-')
ArgumentTypeDescription
conditionFunctionIterator returns true or false.

Returns boolean.

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.

Rule#insertAfter()

Insert new node after old node within the container.

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

Returns Rule.

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 | string[] | ChildNode | ChildNode[] | ChildProps | ChildProps[]New node.

Returns Rule.

Rule#next()

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

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

Returns ChildNode.

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

It represents parent of the current node.

root.nodes[0].parent === root //=> true

Type: ContainerWithChildren<ChildNode>.

Rule#positionBy()

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

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

Returns Position.

Rule#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position.

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

Returns Rule.

Rule#prev()

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

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

Returns ChildNode.

Rule#push()

Add child to the end of the node.

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

Returns Rule.

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, "index" | "word" | "endIndex">Options.

Returns Range.

Rule#raw()

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

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string.

Rule#raws

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

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

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

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

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

Type: RuleRaws.

Rule#remove()

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

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

Returns Rule.

Rule#removeAll()

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

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

Returns Rule.

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

Rule#replaceValues()

ArgumentType
patternstring | RegExp
replacedstring | Function
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
optionsValueOptions
replacedstring | Function

Returns Rule.

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 | ChildNode[] | ChildProps | ChildProps[])[]Mode(s) to replace current one.

Returns Rule.

Rule#root()

Finds the Root instance of the node’s tree.

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

Returns Root.

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#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
conditionFunctionIterator returns true or false.

Returns boolean.

Rule#source

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

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

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

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

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

 atrule.parent.insertBefore(atrule, rule)
}

Type: Source.

Rule#toJSON()

Fix circular links on JSON.stringify().

Returns object.

Rule#toString()

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

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

Returns string.

Rule#type

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

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

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

declaration.type //=> 'decl'

Type: "rule".

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Rule#walkComments()

ArgumentType
callbackFunction

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Rule#warn()

It is a wrapper for Result#warn, providing convenient way of generating warnings.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
ArgumentTypeDescription
resultResult<Document_ | Root>The Result instance that will receive the warning.
messagestringDescription for the warning.
optionsWarningOptionsOptions for the warning.

Returns Warning.

Stringifier

Stringifier#atrule()

ArgumentType
nodeAtRule_
semicolonboolean

Stringifier#beforeAfter()

ArgumentType
nodeAnyNode
detect"after" | "before"

Returns string.

Stringifier#block()

ArgumentType
nodeAnyNode
startstring

Stringifier#body()

ArgumentType
nodeContainer_<ChildNode>

Stringifier#builder

Type: Builder.

Stringifier#comment()

ArgumentType
nodeComment_

Stringifier#decl()

ArgumentType
nodeDeclaration_
semicolonboolean

Stringifier#document()

ArgumentType
nodeDocument_

Stringifier#raw()

ArgumentType
nodeAnyNode
ownstring
detectstring

Returns string.

Stringifier#rawBeforeClose()

ArgumentType
rootRoot

Returns string.

Stringifier#rawBeforeComment()

ArgumentType
rootRoot
nodeComment_

Returns string.

Stringifier#rawBeforeDecl()

ArgumentType
rootRoot
nodeDeclaration_

Returns string.

Stringifier#rawBeforeOpen()

ArgumentType
rootRoot

Returns string.

Stringifier#rawBeforeRule()

ArgumentType
rootRoot

Returns string.

Stringifier#rawColon()

ArgumentType
rootRoot

Returns string.

Stringifier#rawEmptyBody()

ArgumentType
rootRoot

Returns string.

Stringifier#rawIndent()

ArgumentType
rootRoot

Returns string.

Stringifier#rawSemicolon()

ArgumentType
rootRoot

Returns boolean.

Stringifier#rawValue()

ArgumentType
nodeAnyNode
propstring

Returns string.

Stringifier#root()

ArgumentType
nodeRoot

Stringifier#rule()

ArgumentType
nodeRule

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

Warning#plugin

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

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

Type: string.

Warning#text

The warning message.

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

Type: string.

Warning#toString()

Returns a warning position and message.

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

Returns string.

Warning#type

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

Type: "warning".

AtRuleProps

AtRuleProps#name

Name of the at-rule.

Type: string.

AtRuleProps#nodes

Type: (ChildNode | ChildProps)[].

AtRuleProps#params

Parameters following the name of the at-rule.

Type: string | number.

AtRuleProps#raws

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

Type: AtRuleRaws.

AtRuleProps#source

Type: Source.

AtRuleRaws

AtRuleRaws#after

The space symbols after the last child of the node to the end of the node.

Type: string.

AtRuleRaws#afterName

The space between the at-rule name and its parameters.

Type: string.

AtRuleRaws#before

The space symbols before the node. It also stores * and _ symbols before the declaration (IE hack).

Type: string.

AtRuleRaws#between

The symbols between the last parameter and { for rules.

Type: string.

AtRuleRaws#params

The rule’s selector with comments.

Type: Object.

AtRuleRaws#semicolon

Contains true if the last child has an (optional) semicolon.

Type: boolean.

CommentProps

CommentProps#raws

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

Type: CommentRaws.

CommentProps#source

Type: Source.

CommentProps#text

Content of the comment.

Type: string.

CommentRaws

CommentRaws#before

The space symbols before the node.

Type: string.

CommentRaws#left

The space symbols between /* and the comment’s text.

Type: string.

CommentRaws#right

The space symbols between the comment’s text.

Type: string.

ContainerProps

ContainerProps#nodes

Type: (ChildNode | ChildProps)[].

ContainerProps#source

Type: Source.

DeclarationProps

DeclarationProps#important

Whether the declaration has an !important annotation.

Type: boolean.

DeclarationProps#prop

Name of the declaration.

Type: string.

DeclarationProps#raws

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

Type: DeclarationRaws.

DeclarationProps#value

Value of the declaration.

Type: string.

DeclarationRaws

DeclarationRaws#before

The space symbols before the node. It also stores * and _ symbols before the declaration (IE hack).

Type: string.

DeclarationRaws#between

The symbols between the property and value for declarations.

Type: string.

DeclarationRaws#important

The content of the important statement, if it is not just !important.

Type: string.

DeclarationRaws#value

Declaration value with comments.

Type: Object.

DocumentProps

DocumentProps#nodes

Type: Root[].

DocumentProps#raws

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

Every parser saves its own properties.

Type: Record<string, any>.

DocumentProps#source

Type: Source.

FilePosition

FilePosition#column

Column of inclusive start position in source file.

Type: number.

FilePosition#endColumn

Column of exclusive end position in source file.

Type: number.

FilePosition#endLine

Line of exclusive end position in source file.

Type: number.

FilePosition#file

Absolute path to the source file.

Type: string.

FilePosition#line

Line of inclusive start position in source file.

Type: number.

FilePosition#source

Source code.

Type: string.

FilePosition#url

URL for the source file.

Type: string.

Message

Message#plugin

Source PostCSS plugin name.

Type: string.

Message#type

Message type.

Type: string.

Message

Message#plugin

Source PostCSS plugin name.

Type: string.

Message#type

Message type.

Type: string.

NodeErrorOptions

NodeErrorOptions#endIndex

An ending index inside a node's string that should be highlighted as source of error.

Type: number.

NodeErrorOptions#index

An index inside a node's string that should be highlighted as source of error.

Type: number.

NodeErrorOptions#plugin

Plugin name that created this error. PostCSS will set it automatically.

Type: string.

NodeErrorOptions#word

A word inside a node's string, that should be highlighted as source of error.

Type: string.

NodeProps

NodeProps#source

Type: Source.

OldPlugin

ArgumentType
optsT
ArgumentType
rootRoot
resultResult<Document_ | Root>

Returns Transformer.

OldPlugin#postcss

Type: Transformer.

OldPlugin#postcssPlugin

Type: string.

OldPlugin#postcssVersion

Type: string.

Plugin

Plugin#AtRule

Will be called on allAtRule nodes.

Will be called again on node or children changes.

Type: AtRuleProcessor | Object.

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

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

Plugin#DeclarationExit

Will be called on all Declaration nodes.

Will be called again on node or children changes.

Type: DeclarationProcessor | Object.

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

Will be called on Root node once.

Type: RootProcessor.

Plugin#OnceExit

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

Type: RootProcessor.

Plugin#Root

Will be called on Root node.

Will be called again on children changes.

Type: RootProcessor.

Plugin#RootExit

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

Will be called again on children changes.

Type: RootProcessor.

Plugin#Rule

Will be called on all Rule nodes.

Will be called again on node or children changes.

Type: RuleProcessor.

Plugin#RuleExit

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

Will be called again on node or children changes.

Type: RuleProcessor.

Plugin#postcssPlugin

Type: string.

Plugin#prepare

Type: Function.

PluginCreator

ArgumentType
optsPluginOptions

Returns Processor | Plugin.

PluginCreator#postcss

Type: true.

Position

Position#column

Source line in file. In contrast to offset it starts from 1.

Type: number.

Position#line

Source column in file.

Type: number.

Position#offset

Source offset in file. It starts from 0.

Type: number.

ProcessOptions

ProcessOptions#from

The path of the CSS source file. You should always set from, because it is used in source map generation and syntax error messages.

Type: string.

ProcessOptions#map

Source map options

Type: boolean | SourceMapOptions.

ProcessOptions#parser

Function to generate AST by string.

Type: Parser<RootNode> | Syntax<RootNode>.

ProcessOptions#stringifier

Class to generate string by AST.

Type: Stringifier | Syntax<RootNode>.

ProcessOptions#syntax

Object with parse and stringify.

Type: Syntax<RootNode>.

ProcessOptions#to

The path where you'll put the output CSS file. You should always set to to generate correct source maps.

Type: string.

Processor

Processor#plugins

Plugins added to this processor.

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

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

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 | Root | Result<Document_ | Root> | Object | LazyResult_<Document_ | Root>String with input CSS or any object with a toString() method, like a Buffer. Optionally, send a Result instance and the processor will take the Root from it.
ArgumentTypeDescription
cssstring | Root | Result<Document_ | Root> | LazyResult_<Document_ | Root> | ObjectString with input CSS or any object with a toString() method, like a Buffer. Optionally, send a Result instance and the processor will take the Root from it.
optionsProcessOptions<RootNode>

Returns NoWorkResult_ | LazyResult_<Document_ | Root>.

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

Processor#version

Current PostCSS version.

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

Type: string.

Range

Range#end

End position, exclusive.

Type: Position.

Range#start

Start position, inclusive.

Type: Position.

RangePosition

RangePosition#column

The column number in the input.

Type: number.

RangePosition#line

The line number in the input.

Type: number.

Result

Result#css

A CSS string representing of Result#root.

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

Type: string.

Result#lastPlugin

Last runned PostCSS plugin.

Type: Plugin | TransformCallback.

Result#map

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

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

Type: SourceMap.

Result#messages

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

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

Type: Message[].

Result#opts

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

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

Type: ResultOptions.

Result#processor

The Processor instance used for this transformation.

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

Type: Processor.

Result#root

Root node after all transformations.

root.toResult().root === root

Type: RootNode.

Result#toString()

Returns for Result#css content.

result + '' === result.css

Returns string.

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

Result#warnings()

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

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

Returns Warning[].

ResultOptions

ResultOptions#from

The path of the CSS source file. You should always set from, because it is used in source map generation and syntax error messages.

Type: string.

ResultOptions#map

Source map options

Type: boolean | SourceMapOptions.

ResultOptions#node

The CSS node that was the source of the warning.

Type: Node.

ResultOptions#parser

Function to generate AST by string.

Type: Syntax<Document_ | Root> | Parser<Document_ | Root>.

ResultOptions#plugin

Name of plugin that created this warning. Result#warn will fill it automatically with Plugin#postcssPlugin value.

Type: string.

ResultOptions#stringifier

Class to generate string by AST.

Type: Stringifier | Syntax<Document_ | Root>.

ResultOptions#syntax

Object with parse and stringify.

Type: Syntax<Document_ | Root>.

ResultOptions#to

The path where you'll put the output CSS file. You should always set to to generate correct source maps.

Type: string.

Root

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

Returns Root.

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

Returns Root.

Root#assign()

It assigns properties to an existing node instance.

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

Returns Root.

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

Returns Root.

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

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

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

Returns Root.

Root#cloneAfter()

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

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

Returns Root.

Root#cloneBefore()

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

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

Returns Root.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Root#error()

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

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

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

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

This method returns the error instance instead of throwing it.

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

Returns CssSyntaxError_.

Root#every()

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

const noPrefixes = rule.every(i => i.prop[0] !== '-')
ArgumentTypeDescription
conditionFunctionIterator returns true or false.

Returns boolean.

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.

Root#insertAfter()

Insert new node after old node within the container.

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

Returns Root.

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 | string[] | ChildNode | ChildNode[] | ChildProps | ChildProps[]New node.

Returns Root.

Root#next()

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

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

Returns ChildNode.

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

It represents parent of the current node.

root.nodes[0].parent === root //=> true

Type: Document_.

Root#positionBy()

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

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

Returns Position.

Root#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position.

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

Returns Root.

Root#prev()

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

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

Returns ChildNode.

Root#push()

Add child to the end of the node.

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

Returns Root.

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, "index" | "word" | "endIndex">Options.

Returns Range.

Root#raw()

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

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string.

Root#raws

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

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

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

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

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

Type: RootRaws.

Root#remove()

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

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

Returns Root.

Root#removeAll()

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

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

Returns Root.

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

Root#replaceValues()

ArgumentType
patternstring | RegExp
replacedstring | Function
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
optionsValueOptions
replacedstring | Function

Returns Root.

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 | ChildNode[] | ChildProps | ChildProps[])[]Mode(s) to replace current one.

Returns Root.

Root#root()

Finds the Root instance of the node’s tree.

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

Returns Root.

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
conditionFunctionIterator returns true or false.

Returns boolean.

Root#source

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

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

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

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

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

 atrule.parent.insertBefore(atrule, rule)
}

Type: Source.

Root#toJSON()

Fix circular links on JSON.stringify().

Returns 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<Document_ | Root>

Returns Result<Document_ | Root>.

Root#toString()

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

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

Returns string.

Root#type

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

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

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

declaration.type //=> 'decl'

Type: "root".

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Root#walkComments()

ArgumentType
callbackFunction

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Root#warn()

It is a wrapper for warn, providing convenient way of generating warnings.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
ArgumentTypeDescription
resultResult<Document_ | Root>The Result instance that will receive the warning.
messagestringDescription for the warning.
optionsWarningOptionsOptions for the warning.

Returns Warning.

RootProps

RootProps#nodes

Type: (ChildNode | ChildProps)[].

RootProps#raws

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

Type: RootRaws.

RootProps#source

Type: Source.

RootProps

RootProps#nodes

Type: (ChildNode | ChildProps)[].

RootProps#raws

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

Type: RootRaws.

RootProps#source

Type: Source.

RootRaws

RootRaws#after

The space symbols after the last child to the end of file.

Type: string.

RootRaws#codeAfter

Non-CSS code after Root, when Root is inside Document.

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

Type: string.

RootRaws#codeBefore

Non-CSS code before Root, when Root is inside Document.

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

Type: string.

RootRaws#semicolon

Is the last child has an (optional) semicolon.

Type: boolean.

Rule

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

Returns Rule.

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

Returns Rule.

Rule#assign()

It assigns properties to an existing node instance.

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

Returns Rule.

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

Returns Rule.

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

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

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

Returns Rule.

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

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

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Rule#error()

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

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

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

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

This method returns the error instance instead of throwing it.

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

Returns CssSyntaxError_.

Rule#every()

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

const noPrefixes = rule.every(i => i.prop[0] !== '-')
ArgumentTypeDescription
conditionFunctionIterator returns true or false.

Returns boolean.

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.

Rule#insertAfter()

Insert new node after old node within the container.

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

Returns Rule.

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 | string[] | ChildNode | ChildNode[] | ChildProps | ChildProps[]New node.

Returns Rule.

Rule#next()

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

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

Returns ChildNode.

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

It represents parent of the current node.

root.nodes[0].parent === root //=> true

Type: ContainerWithChildren<ChildNode>.

Rule#positionBy()

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

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

Returns Position.

Rule#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position.

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

Returns Rule.

Rule#prev()

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

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

Returns ChildNode.

Rule#push()

Add child to the end of the node.

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

Returns Rule.

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, "index" | "word" | "endIndex">Options.

Returns Range.

Rule#raw()

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

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string.

Rule#raws

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

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

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

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

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

Type: RuleRaws.

Rule#remove()

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

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

Returns Rule.

Rule#removeAll()

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

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

Returns Rule.

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

Rule#replaceValues()

ArgumentType
patternstring | RegExp
replacedstring | Function
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
optionsValueOptions
replacedstring | Function

Returns Rule.

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 | ChildNode[] | ChildProps | ChildProps[])[]Mode(s) to replace current one.

Returns Rule.

Rule#root()

Finds the Root instance of the node’s tree.

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

Returns Root.

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#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
conditionFunctionIterator returns true or false.

Returns boolean.

Rule#source

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

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

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

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

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

 atrule.parent.insertBefore(atrule, rule)
}

Type: Source.

Rule#toJSON()

Fix circular links on JSON.stringify().

Returns object.

Rule#toString()

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

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

Returns string.

Rule#type

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

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

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

declaration.type //=> 'decl'

Type: "rule".

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Rule#walkComments()

ArgumentType
callbackFunction

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

Rule#warn()

It is a wrapper for warn, providing convenient way of generating warnings.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
ArgumentTypeDescription
resultResult<Document_ | Root>The Result instance that will receive the warning.
messagestringDescription for the warning.
optionsWarningOptionsOptions for the warning.

Returns Warning.

RuleProps

RuleProps#nodes

Type: (ChildNode | ChildProps)[].

RuleProps#raws

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

Type: RuleRaws.

RuleProps#selector

Selector or selectors of the rule.

Type: string.

RuleProps#selectors

Selectors of the rule represented as an array of strings.

Type: string[].

RuleProps#source

Type: Source.

RuleProps

RuleProps#nodes

Type: (ChildNode | ChildProps)[].

RuleProps#raws

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

Type: RuleRaws.

RuleProps#selector

Selector or selectors of the rule.

Type: string.

RuleProps#selectors

Selectors of the rule represented as an array of strings.

Type: string[].

RuleProps#source

Type: Source.

RuleRaws

RuleRaws#after

The space symbols after the last child of the node to the end of the node.

Type: string.

RuleRaws#before

The space symbols before the node. It also stores * and _ symbols before the declaration (IE hack).

Type: string.

RuleRaws#between

The symbols between the selector and { for rules.

Type: string.

RuleRaws#ownSemicolon

Contains true if there is semicolon after rule.

Type: string.

RuleRaws#selector

The rule’s selector with comments.

Type: Object.

RuleRaws#semicolon

Contains true if the last child has an (optional) semicolon.

Type: boolean.

Source

Source#end

The inclusive ending position for the source code of a node.

Type: Position.

Source#input

The source file from where a node has originated.

Type: Input_.

Source#start

The inclusive starting position for the source code of a node.

Type: Position.

SourceMapOptions

SourceMapOptions#absolute

Use absolute path in generated source map.

Type: boolean.

SourceMapOptions#annotation

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

Type: string | boolean | Function.

SourceMapOptions#from

Override from in map’s sources.

Type: string.

SourceMapOptions#inline

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

Type: boolean.

SourceMapOptions#prev

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

Type: string | boolean | object | Function.

SourceMapOptions#sourcesContent

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

Type: boolean.

Syntax

Syntax#parse

Function to generate AST by string.

Type: Parser<RootNode>.

Syntax#stringify

Class to generate string by AST.

Type: Stringifier.

Transformer

ArgumentType
rootRoot
resultResult<Document_ | Root>

Returns void | Promise<void>.

Transformer#postcssPlugin

Type: string.

Transformer#postcssVersion

Type: string.

ValueOptions

ValueOptions#fast

String that’s used to narrow down values and speed up the regexp search.

Type: string.

ValueOptions#props

An array of property names.

Type: string[].

Warning

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

Warning#plugin

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

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

Type: string.

Warning#text

The warning message.

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

Type: string.

Warning#toString()

Returns a warning position and message.

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

Returns string.

Warning#type

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

Type: "warning".

WarningOptions

WarningOptions#end

End position, exclusive, in CSS node string that caused the warning.

Type: RangePosition.

WarningOptions#endIndex

End index, exclusive, in CSS node string that caused the warning.

Type: number.

WarningOptions#index

Start index, inclusive, in CSS node string that caused the warning.

Type: number.

WarningOptions#node

CSS node that caused the warning.

Type: Node.

WarningOptions#plugin

Name of the plugin that created this warning. Result#warn fills this property automatically.

Type: string.

WarningOptions#start

Start position, inclusive, in CSS node string that caused the warning.

Type: RangePosition.

WarningOptions#word

Word in CSS source that caused the warning.

Type: string.

WarningOptions

WarningOptions#end

End position, exclusive, in CSS node string that caused the warning.

Type: RangePosition.

WarningOptions#endIndex

End index, exclusive, in CSS node string that caused the warning.

Type: number.

WarningOptions#index

Start index, inclusive, in CSS node string that caused the warning.

Type: number.

WarningOptions#node

CSS node that caused the warning.

Type: Node.

WarningOptions#plugin

Name of the plugin that created this warning. Result#warn fills this property automatically.

Type: string.

WarningOptions#start

Start position, inclusive, in CSS node string that caused the warning.

Type: RangePosition.

WarningOptions#word

Word in CSS source that caused the warning.

Type: string.

at-rule

at-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 | Node | ChildProps | Node[]New node.

Returns AtRule_.

at-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 | string[] | Node | ChildProps | ChildProps[] | Node[])[]New nodes.

Returns AtRule_.

at-rule#assign()

It assigns properties to an existing node instance.

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

Returns AtRule_.

at-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 | Node | ChildProps | Node[]New node.

Returns AtRule_.

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

at-rule#clone()

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

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

Returns AtRule.

at-rule#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 AtRule.

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

Returns AtRule.

at-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
callbackFunctionIterator receives each node and index.

Returns void | false.

at-rule#error()

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

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

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

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

This method returns the error instance instead of throwing it.

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

Returns CssSyntaxError_.

at-rule#every()

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

const noPrefixes = rule.every(i => i.prop[0] !== '-')
ArgumentTypeDescription
conditionFunctionIterator returns true or false.

Returns boolean.

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

at-rule#insertAfter()

Insert new node after old node within the container.

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

Returns AtRule_.

at-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 | string[] | ChildNode | ChildNode[] | ChildProps | ChildProps[]New node.

Returns AtRule_.

at-rule#name

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

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

Type: string.

at-rule#next()

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

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

Returns ChildNode.

at-rule#nodes

An array containing the layer’s children.

const root = postcss.parse('@layer example { a { color: black } }')
const layer = root.first
layer.nodes.length           //=> 1
layer.nodes[0].selector      //=> 'a'

Can be undefinded if the at-rule has no body.

const root = postcss.parse('@layer a, b, c;')
const layer = root.first
layer.nodes //=> undefined

Type: ChildNode[].

at-rule#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.

at-rule#parent

It represents parent of the current node.

root.nodes[0].parent === root //=> true

Type: ContainerWithChildren<ChildNode>.

at-rule#positionBy()

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

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

Returns Position.

at-rule#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position.

at-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 | string[] | Node | ChildProps | ChildProps[] | Node[])[]New nodes.

Returns AtRule_.

at-rule#prev()

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

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

Returns ChildNode.

at-rule#push()

Add child to the end of the node.

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

Returns AtRule_.

at-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, "index" | "word" | "endIndex">Options.

Returns Range.

at-rule#raw()

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

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string.

at-rule#raws

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

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

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

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

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

Type: AtRuleRaws.

at-rule#remove()

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

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

Returns AtRule_.

at-rule#removeAll()

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

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

Returns AtRule_.

at-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 AtRule_.

at-rule#replaceValues()

ArgumentType
patternstring | RegExp
replacedstring | Function
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
optionsValueOptions
replacedstring | Function

Returns AtRule_.

at-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 | ChildNode[] | ChildProps | ChildProps[])[]Mode(s) to replace current one.

Returns AtRule_.

at-rule#root()

Finds the Root instance of the node’s tree.

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

Returns Root.

at-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
conditionFunctionIterator returns true or false.

Returns boolean.

at-rule#source

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

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

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

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

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

 atrule.parent.insertBefore(atrule, rule)
}

Type: Source.

at-rule#toJSON()

Fix circular links on JSON.stringify().

Returns object.

at-rule#toString()

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

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

Returns string.

at-rule#type

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

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

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

declaration.type //=> 'decl'

Type: "atrule".

at-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
callbackFunctionIterator receives each node and index.

Returns void | false.

at-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
callbackFunctionIterator receives each node and index.

Returns void | false.

at-rule#walkComments()

ArgumentType
callbackFunction

Returns void | false.

at-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
callbackFunctionIterator receives each node and index.

Returns void | false.

at-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
callbackFunctionIterator receives each node and index.

Returns void | false.

at-rule#warn()

It is a wrapper for Result#warn, providing convenient way of generating warnings.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
ArgumentTypeDescription
resultResult<Document_ | Root>The Result instance that will receive the warning.
messagestringDescription for the warning.
optionsWarningOptionsOptions for the warning.

Returns Warning.

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

Returns Comment_.

comment#assign()

It assigns properties to an existing node instance.

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

Returns Comment_.

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

Returns Comment_.

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

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

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

Returns Comment.

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

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

comment#error()

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

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

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

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

This method returns the error instance instead of throwing it.

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

Returns CssSyntaxError_.

comment#next()

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

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

Returns ChildNode.

comment#parent

It represents parent of the current node.

root.nodes[0].parent === root //=> true

Type: Container_<ChildNode>.

comment#positionBy()

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

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

Returns Position.

comment#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position.

comment#prev()

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

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

Returns ChildNode.

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, "index" | "word" | "endIndex">Options.

Returns Range.

comment#raw()

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

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string.

comment#raws

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

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

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

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

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

Type: CommentRaws.

comment#remove()

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

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

Returns Comment_.

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 | ChildNode[] | ChildProps | ChildProps[])[]Mode(s) to replace current one.

Returns Comment_.

comment#root()

Finds the Root instance of the node’s tree.

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

Returns Root.

comment#source

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

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

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

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

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

 atrule.parent.insertBefore(atrule, rule)
}

Type: Source.

comment#text

The comment's text.

Type: string.

comment#toJSON()

Fix circular links on JSON.stringify().

Returns object.

comment#toString()

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

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

Returns string.

comment#type

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

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

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

declaration.type //=> 'decl'

Type: "comment".

comment#warn()

It is a wrapper for Result#warn, providing convenient way of generating warnings.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
ArgumentTypeDescription
resultResult<Document_ | Root>The Result instance that will receive the warning.
messagestringDescription for the warning.
optionsWarningOptionsOptions for the warning.

Returns Warning.

container

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

Returns Container_<Child>.

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

Returns Container_<Child>.

container#assign()

It assigns properties to an existing node instance.

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

Returns Container_<Child>.

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

Returns Container_<Child>.

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

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

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

Returns Container<Child>.

container#cloneAfter()

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

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

Returns Container<Child>.

container#cloneBefore()

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

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

Returns Container<Child>.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

container#error()

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

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

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

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

This method returns the error instance instead of throwing it.

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

Returns CssSyntaxError_.

container#every()

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

const noPrefixes = rule.every(i => i.prop[0] !== '-')
ArgumentTypeDescription
conditionFunctionIterator returns true or false.

Returns boolean.

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.

container#insertAfter()

Insert new node after old node within the container.

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

Returns Container_<Child>.

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 | string[] | Child | Child[] | ChildProps | ChildProps[]New node.

Returns Container_<Child>.

container#next()

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

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

Returns ChildNode.

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

It represents parent of the current node.

root.nodes[0].parent === root //=> true

Type: Container_<ChildNode> | Document_.

container#positionBy()

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

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

Returns Position.

container#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position.

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

Returns Container_<Child>.

container#prev()

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

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

Returns ChildNode.

container#push()

Add child to the end of the node.

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

Returns Container_<Child>.

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, "index" | "word" | "endIndex">Options.

Returns Range.

container#raw()

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

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string.

container#raws

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

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

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

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

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

Type: any.

container#remove()

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

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

Returns Container_<Child>.

container#removeAll()

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

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

Returns Container_<Child>.

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 Container_<Child>.

container#replaceValues()

ArgumentType
patternstring | RegExp
replacedstring | Function
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
optionsValueOptions
replacedstring | Function

Returns Container_<Child>.

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 | ChildNode[] | ChildProps | ChildProps[])[]Mode(s) to replace current one.

Returns Container_<Child>.

container#root()

Finds the Root instance of the node’s tree.

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

Returns Root.

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
conditionFunctionIterator returns true or false.

Returns boolean.

container#source

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

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

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

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

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

 atrule.parent.insertBefore(atrule, rule)
}

Type: Source.

container#toJSON()

Fix circular links on JSON.stringify().

Returns object.

container#toString()

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

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

Returns string.

container#type

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

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

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

declaration.type //=> 'decl'

Type: string.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

container#walkComments()

ArgumentType
callbackFunction

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

container#warn()

It is a wrapper for Result#warn, providing convenient way of generating warnings.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
ArgumentTypeDescription
resultResult<Document_ | Root>The Result instance that will receive the warning.
messagestringDescription for the warning.
optionsWarningOptionsOptions for the warning.

Returns Warning.

css-syntax-error

css-syntax-error#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.

css-syntax-error#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.

css-syntax-error#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.

css-syntax-error#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.

css-syntax-error#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.

css-syntax-error#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.

css-syntax-error#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.

css-syntax-error#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".

css-syntax-error#plugin

Plugin name, if error came from plugin.

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

Type: string.

css-syntax-error#reason

Error message.

error.message //=> 'Unclosed block'

Type: string.

css-syntax-error#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.

css-syntax-error#source

Source code of the broken file.

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

Type: string.

css-syntax-error#stack

Type: string.

css-syntax-error#toString()

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

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

Returns string.

declaration

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

Returns Declaration_.

declaration#assign()

It assigns properties to an existing node instance.

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

Returns Declaration_.

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

Returns Declaration_.

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

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

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

Returns Declaration.

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

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

declaration#error()

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

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

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

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

This method returns the error instance instead of throwing it.

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

Returns CssSyntaxError_.

declaration#important

It represents a specificity of the declaration.

If true, the CSS declaration will have an important specifier.

const root = postcss.parse('a { color: black !important; color: red }')

root.first.first.important //=> true
root.first.last.important  //=> undefined

Type: boolean.

declaration#next()

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

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

Returns ChildNode.

declaration#parent

It represents parent of the current node.

root.nodes[0].parent === root //=> true

Type: ContainerWithChildren<ChildNode>.

declaration#positionBy()

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

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

Returns Position.

declaration#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position.

declaration#prev()

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

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

Returns ChildNode.

declaration#prop

The property name for a CSS declaration.

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

decl.prop //=> 'color'

Type: string.

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, "index" | "word" | "endIndex">Options.

Returns Range.

declaration#raw()

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

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string.

declaration#raws

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

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

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

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

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

Type: DeclarationRaws.

declaration#remove()

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

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

Returns Declaration_.

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 | ChildNode[] | ChildProps | ChildProps[])[]Mode(s) to replace current one.

Returns Declaration_.

declaration#root()

Finds the Root instance of the node’s tree.

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

Returns Root.

declaration#source

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

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

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

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

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

 atrule.parent.insertBefore(atrule, rule)
}

Type: Source.

declaration#toJSON()

Fix circular links on JSON.stringify().

Returns object.

declaration#toString()

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

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

Returns string.

declaration#type

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

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

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

declaration.type //=> 'decl'

Type: "decl".

declaration#value

The property value for a CSS declaration.

Any CSS comments inside the value string will be filtered out. CSS comments present in the source value will be available in the raws property.

Assigning new value would ignore the comments in raws property while compiling node to string.

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

decl.value //=> 'black'

Type: string.

declaration#variable

It represents a getter that returns true if a declaration starts with -- or $, which are used to declare variables in CSS and SASS/SCSS.

const root = postcss.parse(':root { --one: 1 }')
const one = root.first.first

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

one.variable //=> true

Type: boolean.

declaration#warn()

It is a wrapper for Result#warn, providing convenient way of generating warnings.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
ArgumentTypeDescription
resultResult<Document_ | Root>The Result instance that will receive the warning.
messagestringDescription for the warning.
optionsWarningOptionsOptions for the warning.

Returns Warning.

document

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

Returns Document_.

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

Returns Document_.

document#assign()

It assigns properties to an existing node instance.

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

Returns Document_.

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

Returns Document_.

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

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

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

Returns Document.

document#cloneAfter()

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

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

Returns Document.

document#cloneBefore()

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

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

Returns Document.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

document#error()

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

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

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

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

This method returns the error instance instead of throwing it.

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

Returns CssSyntaxError_.

document#every()

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

const noPrefixes = rule.every(i => i.prop[0] !== '-')
ArgumentTypeDescription
conditionFunctionIterator returns true or false.

Returns boolean.

document#index()

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

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

Returns number.

document#insertAfter()

Insert new node after old node within the container.

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

Returns Document_.

document#insertBefore()

Insert new node before old node within the container.

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

Returns Document_.

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

Returns ChildNode.

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

document#parent

It represents parent of the current node.

root.nodes[0].parent === root //=> true

Type: undefined.

document#positionBy()

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

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

Returns Position.

document#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position.

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

Returns Document_.

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

Returns ChildNode.

document#push()

Add child to the end of the node.

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

Returns Document_.

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, "index" | "word" | "endIndex">Options.

Returns Range.

document#raw()

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

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string.

document#raws

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

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

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

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

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

Type: any.

document#remove()

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

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

Returns Document_.

document#removeAll()

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

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

Returns Document_.

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 | RootChild or child’s index.

Returns Document_.

document#replaceValues()

ArgumentType
patternstring | RegExp
replacedstring | Function
ArgumentTypeDescription
patternstring | RegExpReplace pattern.
optionsValueOptions
replacedstring | Function

Returns Document_.

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 | ChildNode[] | ChildProps | ChildProps[])[]Mode(s) to replace current one.

Returns Document_.

document#root()

Finds the Root instance of the node’s tree.

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

Returns Root.

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
conditionFunctionIterator returns true or false.

Returns boolean.

document#source

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

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

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

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

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

 atrule.parent.insertBefore(atrule, rule)
}

Type: Source.

document#toJSON()

Fix circular links on JSON.stringify().

Returns 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<Document_ | Root>

Returns Result<Document_ | Root>.

document#toString()

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

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

Returns string.

document#type

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

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

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

declaration.type //=> 'decl'

Type: "document".

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

document#walkComments()

ArgumentType
callbackFunction

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

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
callbackFunctionIterator receives each node and index.

Returns void | false.

document#warn()

It is a wrapper for Result#warn, providing convenient way of generating warnings.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
ArgumentTypeDescription
resultResult<Document_ | Root>The Result instance that will receive the warning.
messagestringDescription for the warning.
optionsWarningOptionsOptions for the warning.

Returns Warning.

fromJSON

ArgumentType
dataobject
ArgumentType
dataobject[]

Returns Node.

input

input#css

Input CSS source.

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

Type: string.

input#error()

ArgumentType
messagestring
startObject | Object
endObject | Object
optsObject
ArgumentType
messagestring
linenumber
columnnumber
optsObject
ArgumentType
messagestring
offsetnumber
optsObject

Returns CssSyntaxError_.

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

Converts source offset to line and column.

ArgumentTypeDescription
offsetnumberSource offset.

Returns Object.

input#hasBOM

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

Type: boolean.

input#id

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

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

Type: string.

input#map

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

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

Type: PreviousMap_.

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

lazy-result

lazy-result#async()

Run plugin in async way and return Result.

Returns Promise<Result<RootNode>>.

lazy-result#catch

Type: Function.

lazy-result#finally

Type: Function.

lazy-result#sync()

Run plugin in sync way and return Result.

Returns Result<RootNode>.

lazy-result#then

Type: Function.

lazy-result#toString()

Alias for the LazyResult#css property.

lazy + '' === lazy.css

Returns string.

lazy-result#warnings()

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

Returns Warning[].

no-work-result

no-work-result#async()

Run plugin in async way and return Result.

Returns Promise<Result<Root>>.

no-work-result#catch

Type: Function.

no-work-result#finally

Type: Function.

no-work-result#sync()

Run plugin in sync way and return Result.

Returns Result<Root>.

no-work-result#then

Type: Function.

no-work-result#toString()

Alias for the LazyResult#css property.

lazy + '' === lazy.css

Returns string.

no-work-result#warnings()

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

Returns Warning[].

node

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

Returns Node.

node#assign()

It assigns properties to an existing node instance.

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

Returns Node.

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

Returns Node.

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

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

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

Returns 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 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 Node.

node#error()

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

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

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

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

This method returns the error instance instead of throwing it.

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

Returns CssSyntaxError_.

node#next()

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

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

Returns ChildNode.

node#parent

It represents parent of the current node.

root.nodes[0].parent === root //=> true

Type: Container_<ChildNode> | Document_.

node#positionBy()

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

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

Returns Position.

node#positionInside()

Convert string index to line/column.

ArgumentTypeDescription
indexnumberThe symbol number in the node’s string.

Returns Position.

node#prev()

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

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

Returns ChildNode.

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, "index" | "word" | "endIndex">Options.

Returns Range.

node#raw()

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

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
ArgumentTypeDescription
propstringName of code style property.
defaultTypestringName of default value, it can be missed if the value is the same as prop.

Returns string.

node#raws

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

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

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

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

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

Type: any.

node#remove()

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

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

Returns Node.

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 | ChildNode[] | ChildProps | ChildProps[])[]Mode(s) to replace current one.

Returns Node.

node#root()

Finds the Root instance of the node’s tree.

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

Returns Root.

node#source

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

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

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

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

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

 atrule.parent.insertBefore(atrule, rule)
}

Type: Source.

node#toJSON()

Fix circular links on JSON.stringify().

Returns object.

node#toString()

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

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

Returns string.

node#type

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

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

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

declaration.type //=> 'decl'

Type: string.

node#warn()

It is a wrapper for Result#warn, providing convenient way of generating warnings.

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
ArgumentTypeDescription
resultResult<Document_ | Root>The Result instance that will receive the warning.
messagestringDescription for the warning.
optionsWarningOptionsOptions for the warning.

Returns Warning.

previous-map

previous-map#annotation

sourceMappingURL content.

Type: string.

previous-map#consumer()

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

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

Returns SourceMapConsumer.

previous-map#file

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

Type: string.

previous-map#inline

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

Type: boolean.

previous-map#mapFile

Path to source map file.

Type: string.

previous-map#root

The directory with source map file, if source map is in separated file.

Type: string.

previous-map#text

Source map file content.

Type: string.

previous-map#withContent()

Does source map contains sourcesContent with input source text.

Returns boolean.

stringifier

stringifier#atrule()

ArgumentType
nodeAtRule_
semicolonboolean

stringifier#beforeAfter()

ArgumentType
nodeAnyNode
detect"after" | "before"

Returns string.

stringifier#block()

ArgumentType
nodeAnyNode
startstring

stringifier#body()

ArgumentType
nodeContainer_<ChildNode>

stringifier#builder

Type: Builder.

stringifier#comment()

ArgumentType
nodeComment_

stringifier#decl()

ArgumentType
nodeDeclaration_
semicolonboolean

stringifier#document()

ArgumentType
nodeDocument_

stringifier#raw()

ArgumentType
nodeAnyNode
ownstring
detectstring

Returns string.

stringifier#rawBeforeClose()

ArgumentType
rootRoot

Returns string.

stringifier#rawBeforeComment()

ArgumentType
rootRoot
nodeComment_

Returns string.

stringifier#rawBeforeDecl()

ArgumentType
rootRoot
nodeDeclaration_

Returns string.

stringifier#rawBeforeOpen()

ArgumentType
rootRoot

Returns string.

stringifier#rawBeforeRule()

ArgumentType
rootRoot

Returns string.

stringifier#rawColon()

ArgumentType
rootRoot

Returns string.

stringifier#rawEmptyBody()

ArgumentType
rootRoot

Returns string.

stringifier#rawIndent()

ArgumentType
rootRoot

Returns string.

stringifier#rawSemicolon()

ArgumentType
rootRoot

Returns boolean.

stringifier#rawValue()

ArgumentType
nodeAnyNode
propstring

Returns string.

stringifier#root()

ArgumentType
nodeRoot

stringifier#rule()

ArgumentType
nodeRule

stringifier#stringify()

ArgumentType
nodeAnyNode
semicolonboolean