AtRule
(defaults)
Represents an at-rule.
If it’s followed in the CSS by a {} block, this node will have a nodes property representing its children.
parameter | type | description |
---|---|---|
defaults |
any |
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 //=> []
append
(children)
Inserts new nodes to the end of the container.
parameter | type | description |
---|---|---|
children |
...(Node | object | string | Array<Node>) | New nodes. |
Node
:
This node for methods chain.
const decl1 = postcss.decl({ prop: 'color', value: 'black' })
const decl2 = postcss.decl({ 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')
each
(callback)
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.
parameter | type | description |
---|---|---|
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
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
})
every
(condition)
Returns true
if callback returns true
for all of the container’s children.
parameter | type | description |
---|---|---|
condition |
childCondition | Iterator returns true or false. |
boolean
:
Is every child pass condition.
const noPrefixes = rule.every(i => i.prop[0] !== '-')
first
()
The container’s first child.
Type: Node
rule.first === rules.nodes[0]
index
(child)
Returns a child
’s index within the Container#nodes array.
parameter | type | description |
---|---|---|
child |
Node | Child of the current container. |
number
:
Child index.
rule.index( rule.nodes[2] ) //=> 2
insertAfter
(exist, add)
Insert new node after old node within the container.
parameter | type | description |
---|---|---|
exist |
(Node | number) | Child or child’s index. |
add |
(Node | object | string | Array<Node>) | New node. |
Node
:
This node for methods chain.
insertBefore
(exist, add)
Insert new node before old node within the container.
parameter | type | description |
---|---|---|
exist |
(Node | number) | Child or child’s index. |
add |
(Node | object | string | Array<Node>) | New node. |
Node
:
This node for methods chain.
rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
last
()
The container’s last child.
Type: Node
rule.last === rule.nodes[rule.nodes.length - 1]
prepend
(children)
Inserts new nodes to the start of the container.
parameter | type | description |
---|---|---|
children |
...(Node | object | string | Array<Node>) | New nodes. |
Node
:
This node for methods chain.
const decl1 = postcss.decl({ prop: 'color', value: 'black' })
const decl2 = postcss.decl({ 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')
removeAll
()
Removes all children from the container and cleans their parent properties.
Node
:
This node for methods chain.
rule.removeAll()
rule.nodes.length //=> 0
removeChild
(child)
Removes node from the container and cleans the parent properties from the node and its children.
parameter | type | description |
---|---|---|
child |
(Node | number) | Child or child’s index. |
Node
:
This node for methods chain
rule.nodes.length //=> 5
rule.removeChild(decl)
rule.nodes.length //=> 4
decl.parent //=> undefined
replaceValues
(pattern, opts, callback)
Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.
This method is useful if you are using a custom unit or function and need to iterate through all values.
parameter | type | description |
---|---|---|
pattern |
(string | RegExp) | Replace pattern. |
opts |
object | Options to speed up the search. |
opts.props | (string | Array<string>) | An array of property names. |
opts.fast | string | String that’s used to narrow down values and speed up the regexp search. |
callback |
(function | string) | String to replace pattern or callback
that returns a new value. The callback
will receive the same arguments
as those passed to a function parameter
of
String#replace
.
|
Node
:
This node for methods chain.
root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
return 15 * parseInt(string) + 'px'
})
some
(condition)
Returns true
if callback returns true
for (at least) one
of the container’s children.
parameter | type | description |
---|---|---|
condition |
childCondition | Iterator returns true or false. |
boolean
:
Is some child pass condition.
const hasPrefix = rule.some(i => i.prop[0] === '-')
walk
(callback)
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.
parameter | type | description |
---|---|---|
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
root.walk(node => {
// Traverses all descendant nodes.
})
walkAtRules
(name?, callback)
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.
parameter | type | description |
---|---|---|
name |
(string | RegExp)? | String or regular expression to filter at-rules by name. |
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
root.walkAtRules(rule => {
if (isOld(rule.name)) rule.remove()
})
let first = false
root.walkAtRules('charset', rule => {
if (!first) {
first = true
} else {
rule.remove()
}
})
walkComments
(callback)
Traverses the container’s descendant nodes, calling callback for each comment node.
Like Container#each, this method is safe to use if you are mutating arrays during iteration.
parameter | type | description |
---|---|---|
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
root.walkComments(comment => {
comment.remove()
})
walkDecls
(prop?, callback)
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.
Like Container#each, this method is safe to use if you are mutating arrays during iteration.
parameter | type | description |
---|---|---|
prop |
(string | RegExp)? | String or regular expression to filter declarations by property name. |
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
root.walkDecls(decl => {
checkPropertySupport(decl.prop)
})
root.walkDecls('border-radius', decl => {
decl.remove()
})
root.walkDecls(/^background/, decl => {
decl.value = takeFirstColorFromGradient(decl.value)
})
walkRules
(selector?, callback)
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.
parameter | type | description |
---|---|---|
selector |
(string | RegExp)? | String or regular expression to filter rules by selector. |
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
returns
false
if iteration was broke.
const selectors = []
root.walkRules(rule => {
selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
Comment
(defaults)
Represents a comment between declarations or statements (rule and at-rules).
Comments inside selectors, at-rule parameters, or declaration values
will be stored in the raws
properties explained above.
parameter | type | description |
---|---|---|
defaults |
any |
after
(add)
Insert new node after current node to current node’s parent.
Just alias for node.parent.insertAfter(node, add)
.
parameter | type | description |
---|---|---|
add |
(Node | object | string | Array<Node>) | New node. |
Node
:
This node for methods chain.
decl.after('color: black')
before
(add)
Insert new node before current node to current node’s parent.
Just alias for node.parent.insertBefore(node, add)
.
parameter | type | description |
---|---|---|
add |
(Node | object | string | Array<Node>) | New node. |
Node
:
This node for methods chain.
decl.before('content: ""')
cleanRaws
(keepBetween?)
Clear the code style properties for the node and its children.
parameter | type | description |
---|---|---|
keepBetween |
boolean? | Keep the raws.between symbols. |
undefined
:
node.raws.before //=> ' '
node.cleanRaws()
node.raws.before //=> undefined
clone
(overrides = {})
Returns an exact clone of the node.
The resulting cloned node and its (cloned) children will retain code style properties.
parameter | type | description |
---|---|---|
overrides |
object?
= {}
|
New properties to override in the clone. |
Node
:
Clone of the node.
decl.raws.before //=> "\n "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before //=> "\n "
cloned.toString() //=> -moz-transform: scale(0)
cloneAfter
(overrides = {})
Shortcut to clone the node and insert the resulting cloned node after the current node.
parameter | type | description |
---|---|---|
overrides |
object?
= {}
|
New properties to override in the clone. |
Node
:
New node.
cloneBefore
(overrides = {})
Shortcut to clone the node and insert the resulting cloned node before the current node.
parameter | type | description |
---|---|---|
overrides |
object?
= {}
|
Mew properties to override in the clone. |
Node
:
New node
decl.cloneBefore({ prop: '-moz-' + decl.prop })
error
(message, opts = {})
Returns a CssSyntaxError
instance containing the original position
of the node in the source, showing line and column numbers and also
a small excerpt to facilitate debugging.
If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).
This method produces very useful error messages.
parameter | type | description |
---|---|---|
message |
string | Error description. |
opts |
object?
= {}
|
Options. |
opts.plugin | string | Plugin name that created this error. PostCSS will set it automatically. |
opts.word | string | A word inside a node’s string that should be highlighted as the source of the error. |
opts.index | number | An index inside a node’s string that should be highlighted as the source of the error. |
CssSyntaxError
:
Error object to throw 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
}
next
()
Returns the next child of the node’s parent.
Returns undefined
if the current node is the last child.
(Node | undefined)
:
Next node.
if (comment.text === 'delete next') {
const next = comment.next()
if (next) {
next.remove()
}
}
prev
()
Returns the previous child of the node’s parent.
Returns undefined
if the current node is the first child.
(Node | undefined)
:
Previous node.
const annotation = decl.prev()
if (annotation.type === 'comment') {
readAnnotation(annotation.text)
}
raw
(prop, defaultType?)
Returns a Node#raws value. If the node is missing the code style property (because the node was manually built or cloned), PostCSS will try to autodetect the code style property by looking at other nodes in the tree.
parameter | type | description |
---|---|---|
prop |
string | Name of code style property. |
defaultType |
string? | Name of default value, it can be missed if the value is the same as prop. |
string
:
Code style value.
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') //=> ' '
remove
()
Removes the node from its parent and cleans the parent properties from the node and its children.
Node
:
Node to make calls chain.
if (decl.prop.match(/^-webkit-/)) {
decl.remove()
}
replaceWith
(nodes)
Inserts node(s) before the current node and removes the current node.
parameter | type | description |
---|---|---|
nodes |
...Node | Mode(s) to replace current one. |
Node
:
Current node to methods chain.
if (atrule.name === 'mixin') {
atrule.replaceWith(mixinRules[atrule.params])
}
root
()
Finds the Root instance of the node’s tree.
Root
:
Root parent.
root.nodes[0].nodes[0].root() === root
toString
(stringifier = stringify)
Returns a CSS string representing the node.
parameter | type | description |
---|---|---|
stringifier |
(stringifier | syntax)?
= stringify
|
A syntax to use in string generation. |
string
:
CSS string of this node.
postcss.rule({ selector: 'a' }).toString() //=> "a {}"
warn
(result, text, opts?)
This method is provided as a convenience wrapper for Result#warn.
parameter | type | description |
---|---|---|
result |
Result | The Result instance that will receive the warning. |
text |
string | Warning message. |
opts |
object? | Options |
opts.plugin | string | Plugin name that created this warning. PostCSS will set it automatically. |
opts.word | string | A word inside a node’s string that should be highlighted as the source of the warning. |
opts.index | number | An index inside a node’s string that should be highlighted as the source of the warning. |
Warning
:
Created warning object.
const plugin = postcss.plugin('postcss-deprecated', () => {
return (root, result) => {
root.walkDecls('bad', decl => {
decl.warn(result, 'Deprecated property bad')
})
}
})
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.
after
(add)
Insert new node after current node to current node’s parent.
Just alias for node.parent.insertAfter(node, add)
.
parameter | type | description |
---|---|---|
add |
(Node | object | string | Array<Node>) | New node. |
Node
:
This node for methods chain.
decl.after('color: black')
append
(children)
Inserts new nodes to the end of the container.
parameter | type | description |
---|---|---|
children |
...(Node | object | string | Array<Node>) | New nodes. |
Node
:
This node for methods chain.
const decl1 = postcss.decl({ prop: 'color', value: 'black' })
const decl2 = postcss.decl({ 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')
before
(add)
Insert new node before current node to current node’s parent.
Just alias for node.parent.insertBefore(node, add)
.
parameter | type | description |
---|---|---|
add |
(Node | object | string | Array<Node>) | New node. |
Node
:
This node for methods chain.
decl.before('content: ""')
cleanRaws
(keepBetween?)
Clear the code style properties for the node and its children.
parameter | type | description |
---|---|---|
keepBetween |
boolean? | Keep the raws.between symbols. |
undefined
:
node.raws.before //=> ' '
node.cleanRaws()
node.raws.before //=> undefined
clone
(overrides = {})
Returns an exact clone of the node.
The resulting cloned node and its (cloned) children will retain code style properties.
parameter | type | description |
---|---|---|
overrides |
object?
= {}
|
New properties to override in the clone. |
Node
:
Clone of the node.
decl.raws.before //=> "\n "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before //=> "\n "
cloned.toString() //=> -moz-transform: scale(0)
cloneAfter
(overrides = {})
Shortcut to clone the node and insert the resulting cloned node after the current node.
parameter | type | description |
---|---|---|
overrides |
object?
= {}
|
New properties to override in the clone. |
Node
:
New node.
cloneBefore
(overrides = {})
Shortcut to clone the node and insert the resulting cloned node before the current node.
parameter | type | description |
---|---|---|
overrides |
object?
= {}
|
Mew properties to override in the clone. |
Node
:
New node
decl.cloneBefore({ prop: '-moz-' + decl.prop })
each
(callback)
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.
parameter | type | description |
---|---|---|
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
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
})
error
(message, opts = {})
Returns a CssSyntaxError
instance containing the original position
of the node in the source, showing line and column numbers and also
a small excerpt to facilitate debugging.
If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).
This method produces very useful error messages.
parameter | type | description |
---|---|---|
message |
string | Error description. |
opts |
object?
= {}
|
Options. |
opts.plugin | string | Plugin name that created this error. PostCSS will set it automatically. |
opts.word | string | A word inside a node’s string that should be highlighted as the source of the error. |
opts.index | number | An index inside a node’s string that should be highlighted as the source of the error. |
CssSyntaxError
:
Error object to throw 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
}
every
(condition)
Returns true
if callback returns true
for all of the container’s children.
parameter | type | description |
---|---|---|
condition |
childCondition | Iterator returns true or false. |
boolean
:
Is every child pass condition.
const noPrefixes = rule.every(i => i.prop[0] !== '-')
first
()
The container’s first child.
Type: Node
rule.first === rules.nodes[0]
index
(child)
Returns a child
’s index within the Container#nodes array.
parameter | type | description |
---|---|---|
child |
Node | Child of the current container. |
number
:
Child index.
rule.index( rule.nodes[2] ) //=> 2
insertAfter
(exist, add)
Insert new node after old node within the container.
parameter | type | description |
---|---|---|
exist |
(Node | number) | Child or child’s index. |
add |
(Node | object | string | Array<Node>) | New node. |
Node
:
This node for methods chain.
insertBefore
(exist, add)
Insert new node before old node within the container.
parameter | type | description |
---|---|---|
exist |
(Node | number) | Child or child’s index. |
add |
(Node | object | string | Array<Node>) | New node. |
Node
:
This node for methods chain.
rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
last
()
The container’s last child.
Type: Node
rule.last === rule.nodes[rule.nodes.length - 1]
next
()
Returns the next child of the node’s parent.
Returns undefined
if the current node is the last child.
(Node | undefined)
:
Next node.
if (comment.text === 'delete next') {
const next = comment.next()
if (next) {
next.remove()
}
}
prepend
(children)
Inserts new nodes to the start of the container.
parameter | type | description |
---|---|---|
children |
...(Node | object | string | Array<Node>) | New nodes. |
Node
:
This node for methods chain.
const decl1 = postcss.decl({ prop: 'color', value: 'black' })
const decl2 = postcss.decl({ 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')
prev
()
Returns the previous child of the node’s parent.
Returns undefined
if the current node is the first child.
(Node | undefined)
:
Previous node.
const annotation = decl.prev()
if (annotation.type === 'comment') {
readAnnotation(annotation.text)
}
raw
(prop, defaultType?)
Returns a Node#raws value. If the node is missing the code style property (because the node was manually built or cloned), PostCSS will try to autodetect the code style property by looking at other nodes in the tree.
parameter | type | description |
---|---|---|
prop |
string | Name of code style property. |
defaultType |
string? | Name of default value, it can be missed if the value is the same as prop. |
string
:
Code style value.
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') //=> ' '
remove
()
Removes the node from its parent and cleans the parent properties from the node and its children.
Node
:
Node to make calls chain.
if (decl.prop.match(/^-webkit-/)) {
decl.remove()
}
removeAll
()
Removes all children from the container and cleans their parent properties.
Node
:
This node for methods chain.
rule.removeAll()
rule.nodes.length //=> 0
removeChild
(child)
Removes node from the container and cleans the parent properties from the node and its children.
parameter | type | description |
---|---|---|
child |
(Node | number) | Child or child’s index. |
Node
:
This node for methods chain
rule.nodes.length //=> 5
rule.removeChild(decl)
rule.nodes.length //=> 4
decl.parent //=> undefined
replaceValues
(pattern, opts, callback)
Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.
This method is useful if you are using a custom unit or function and need to iterate through all values.
parameter | type | description |
---|---|---|
pattern |
(string | RegExp) | Replace pattern. |
opts |
object | Options to speed up the search. |
opts.props | (string | Array<string>) | An array of property names. |
opts.fast | string | String that’s used to narrow down values and speed up the regexp search. |
callback |
(function | string) | String to replace pattern or callback
that returns a new value. The callback
will receive the same arguments
as those passed to a function parameter
of
String#replace
.
|
Node
:
This node for methods chain.
root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
return 15 * parseInt(string) + 'px'
})
replaceWith
(nodes)
Inserts node(s) before the current node and removes the current node.
parameter | type | description |
---|---|---|
nodes |
...Node | Mode(s) to replace current one. |
Node
:
Current node to methods chain.
if (atrule.name === 'mixin') {
atrule.replaceWith(mixinRules[atrule.params])
}
root
()
Finds the Root instance of the node’s tree.
Root
:
Root parent.
root.nodes[0].nodes[0].root() === root
some
(condition)
Returns true
if callback returns true
for (at least) one
of the container’s children.
parameter | type | description |
---|---|---|
condition |
childCondition | Iterator returns true or false. |
boolean
:
Is some child pass condition.
const hasPrefix = rule.some(i => i.prop[0] === '-')
toString
(stringifier = stringify)
Returns a CSS string representing the node.
parameter | type | description |
---|---|---|
stringifier |
(stringifier | syntax)?
= stringify
|
A syntax to use in string generation. |
string
:
CSS string of this node.
postcss.rule({ selector: 'a' }).toString() //=> "a {}"
walk
(callback)
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.
parameter | type | description |
---|---|---|
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
root.walk(node => {
// Traverses all descendant nodes.
})
walkAtRules
(name?, callback)
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.
parameter | type | description |
---|---|---|
name |
(string | RegExp)? | String or regular expression to filter at-rules by name. |
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
root.walkAtRules(rule => {
if (isOld(rule.name)) rule.remove()
})
let first = false
root.walkAtRules('charset', rule => {
if (!first) {
first = true
} else {
rule.remove()
}
})
walkComments
(callback)
Traverses the container’s descendant nodes, calling callback for each comment node.
Like Container#each, this method is safe to use if you are mutating arrays during iteration.
parameter | type | description |
---|---|---|
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
root.walkComments(comment => {
comment.remove()
})
walkDecls
(prop?, callback)
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.
Like Container#each, this method is safe to use if you are mutating arrays during iteration.
parameter | type | description |
---|---|---|
prop |
(string | RegExp)? | String or regular expression to filter declarations by property name. |
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
root.walkDecls(decl => {
checkPropertySupport(decl.prop)
})
root.walkDecls('border-radius', decl => {
decl.remove()
})
root.walkDecls(/^background/, decl => {
decl.value = takeFirstColorFromGradient(decl.value)
})
walkRules
(selector?, callback)
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.
parameter | type | description |
---|---|---|
selector |
(string | RegExp)? | String or regular expression to filter rules by selector. |
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
returns
false
if iteration was broke.
const selectors = []
root.walkRules(rule => {
selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
warn
(result, text, opts?)
This method is provided as a convenience wrapper for Result#warn.
parameter | type | description |
---|---|---|
result |
Result | The Result instance that will receive the warning. |
text |
string | Warning message. |
opts |
object? | Options |
opts.plugin | string | Plugin name that created this warning. PostCSS will set it automatically. |
opts.word | string | A word inside a node’s string that should be highlighted as the source of the warning. |
opts.index | number | An index inside a node’s string that should be highlighted as the source of the warning. |
Warning
:
Created warning object.
const plugin = postcss.plugin('postcss-deprecated', () => {
return (root, result) => {
root.walkDecls('bad', decl => {
decl.warn(result, 'Deprecated property bad')
})
}
})
CssSyntaxError
(message, line?, column?, source?, file?, plugin?)
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
.
parameter | type | description |
---|---|---|
message |
string | Error message. |
line |
number? | Source line of the error. |
column |
number? | Source column of the error. |
source |
string? | Source code of the broken file. |
file |
string? | Absolute path to the broken file. |
plugin |
string? | PostCSS plugin name, if error came from plugin. |
// Catching and checking syntax error
try {
postcss.parse('a{')
} catch (error) {
if (error.name === 'CssSyntaxError') {
error //=> CssSyntaxError
}
}
// Raising error from plugin
throw node.error('Unknown variable', { plugin: 'postcss-vars' })
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.
Type: string
if (error.name === 'CssSyntaxError') {
error //=> CssSyntaxError
}
reason
()
Error message.
Type: string
error.message //=> 'Unclosed block'
file
()
Absolute path to the broken file.
Type: string
error.file //=> 'a.sass'
error.input.file //=> 'a.css'
source
()
Source code of the broken file.
Type: string
error.source //=> 'a { b {} }'
error.input.column //=> 'a b { }'
plugin
()
Plugin name, if error came from plugin.
Type: string
error.plugin //=> 'postcss-vars'
line
()
Source line of the error.
Type: number
error.line //=> 2
error.input.line //=> 4
column
()
Source column of the error.
Type: number
error.column //=> 1
error.input.column //=> 4
message
()
Full error text in the GNU error format with plugin, file, line and column.
Type: string
error.message //=> 'a.css:1:1: Unclosed block'
showSourceCode
(color?)
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.
parameter | type | description |
---|---|---|
color |
boolean? | Whether 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
.
|
string
:
Few lines of CSS source that caused the error.
error.showSourceCode() //=> " 4 | }
// 5 | a {
// > 6 | bad
// | ^
// 7 | }
// 8 | b {"
toString
()
Returns error position, message and source code of the broken part.
string
:
Error position, message and source code.
error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block
// > 1 | a {
// | ^"
Declaration
(defaults)
Represents a CSS declaration.
parameter | type | description |
---|---|---|
defaults |
any |
const root = postcss.parse('a { color: black }')
const decl = root.first.first
decl.type //=> 'decl'
decl.toString() //=> ' color: black'
after
(add)
Insert new node after current node to current node’s parent.
Just alias for node.parent.insertAfter(node, add)
.
parameter | type | description |
---|---|---|
add |
(Node | object | string | Array<Node>) | New node. |
Node
:
This node for methods chain.
decl.after('color: black')
before
(add)
Insert new node before current node to current node’s parent.
Just alias for node.parent.insertBefore(node, add)
.
parameter | type | description |
---|---|---|
add |
(Node | object | string | Array<Node>) | New node. |
Node
:
This node for methods chain.
decl.before('content: ""')
cleanRaws
(keepBetween?)
Clear the code style properties for the node and its children.
parameter | type | description |
---|---|---|
keepBetween |
boolean? | Keep the raws.between symbols. |
undefined
:
node.raws.before //=> ' '
node.cleanRaws()
node.raws.before //=> undefined
clone
(overrides = {})
Returns an exact clone of the node.
The resulting cloned node and its (cloned) children will retain code style properties.
parameter | type | description |
---|---|---|
overrides |
object?
= {}
|
New properties to override in the clone. |
Node
:
Clone of the node.
decl.raws.before //=> "\n "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before //=> "\n "
cloned.toString() //=> -moz-transform: scale(0)
cloneAfter
(overrides = {})
Shortcut to clone the node and insert the resulting cloned node after the current node.
parameter | type | description |
---|---|---|
overrides |
object?
= {}
|
New properties to override in the clone. |
Node
:
New node.
cloneBefore
(overrides = {})
Shortcut to clone the node and insert the resulting cloned node before the current node.
parameter | type | description |
---|---|---|
overrides |
object?
= {}
|
Mew properties to override in the clone. |
Node
:
New node
decl.cloneBefore({ prop: '-moz-' + decl.prop })
error
(message, opts = {})
Returns a CssSyntaxError
instance containing the original position
of the node in the source, showing line and column numbers and also
a small excerpt to facilitate debugging.
If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).
This method produces very useful error messages.
parameter | type | description |
---|---|---|
message |
string | Error description. |
opts |
object?
= {}
|
Options. |
opts.plugin | string | Plugin name that created this error. PostCSS will set it automatically. |
opts.word | string | A word inside a node’s string that should be highlighted as the source of the error. |
opts.index | number | An index inside a node’s string that should be highlighted as the source of the error. |
CssSyntaxError
:
Error object to throw 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
}
next
()
Returns the next child of the node’s parent.
Returns undefined
if the current node is the last child.
(Node | undefined)
:
Next node.
if (comment.text === 'delete next') {
const next = comment.next()
if (next) {
next.remove()
}
}
prev
()
Returns the previous child of the node’s parent.
Returns undefined
if the current node is the first child.
(Node | undefined)
:
Previous node.
const annotation = decl.prev()
if (annotation.type === 'comment') {
readAnnotation(annotation.text)
}
raw
(prop, defaultType?)
Returns a Node#raws value. If the node is missing the code style property (because the node was manually built or cloned), PostCSS will try to autodetect the code style property by looking at other nodes in the tree.
parameter | type | description |
---|---|---|
prop |
string | Name of code style property. |
defaultType |
string? | Name of default value, it can be missed if the value is the same as prop. |
string
:
Code style value.
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') //=> ' '
remove
()
Removes the node from its parent and cleans the parent properties from the node and its children.
Node
:
Node to make calls chain.
if (decl.prop.match(/^-webkit-/)) {
decl.remove()
}
replaceWith
(nodes)
Inserts node(s) before the current node and removes the current node.
parameter | type | description |
---|---|---|
nodes |
...Node | Mode(s) to replace current one. |
Node
:
Current node to methods chain.
if (atrule.name === 'mixin') {
atrule.replaceWith(mixinRules[atrule.params])
}
root
()
Finds the Root instance of the node’s tree.
Root
:
Root parent.
root.nodes[0].nodes[0].root() === root
toString
(stringifier = stringify)
Returns a CSS string representing the node.
parameter | type | description |
---|---|---|
stringifier |
(stringifier | syntax)?
= stringify
|
A syntax to use in string generation. |
string
:
CSS string of this node.
postcss.rule({ selector: 'a' }).toString() //=> "a {}"
warn
(result, text, opts?)
This method is provided as a convenience wrapper for Result#warn.
parameter | type | description |
---|---|---|
result |
Result | The Result instance that will receive the warning. |
text |
string | Warning message. |
opts |
object? | Options |
opts.plugin | string | Plugin name that created this warning. PostCSS will set it automatically. |
opts.word | string | A word inside a node’s string that should be highlighted as the source of the warning. |
opts.index | number | An index inside a node’s string that should be highlighted as the source of the warning. |
Warning
:
Created warning object.
const plugin = postcss.plugin('postcss-deprecated', () => {
return (root, result) => {
root.walkDecls('bad', decl => {
decl.warn(result, 'Deprecated property bad')
})
}
})
Input
(css, opts = {})
Represents the source CSS.
parameter | type | description |
---|---|---|
css |
string | Input CSS source. |
opts |
object?
= {}
|
Processor#process options. |
const root = postcss.parse(css, { from: file })
const input = root.source.input
css
()
Input CSS source
Type: string
const input = postcss.parse('a{}', { from: file }).input
input.css //=> "a{}"
file
()
The absolute path to the CSS source file defined
with the from
option.
Type: string
const root = postcss.parse(css, { from: 'a.css' })
root.source.input.file //=> '/home/ai/a.css'
map
()
The input source map passed from a compilation step before PostCSS (for example, from Sass compiler).
Type: PreviousMap
root.source.input.map.consumer().sources //=> ['a.sass']
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).
Type: string
const root = postcss.parse(css)
root.source.input.file //=> undefined
root.source.input.id //=> "<input css 8LZeVF>"
origin
(line, column)
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).
parameter | type | description |
---|---|---|
line |
number | Line in input CSS. |
column |
number | Column in input CSS. |
filePosition
:
Position in input source.
root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }
from
()
The CSS source identifier. Contains Input#file if the user
set the from
option, or Input#id if they did not.
Type: string
const root = postcss.parse(css, { from: 'a.css' })
root.source.input.from //=> "/home/ai/a.css"
const root = postcss.parse(css)
root.source.input.from //=> "<input css 1>"
LazyResult
(processor, css, opts)
A Promise proxy for the result of PostCSS transformations.
A LazyResult
instance is returned by Processor#process.
parameter | type | description |
---|---|---|
processor |
any | |
css |
any | |
opts |
any |
const lazy = postcss([autoprefixer]).process(css)
processor
()
Returns a Processor instance, which will be used for CSS transformations.
Type: Processor
opts
()
Options from the Processor#process call.
Type: processOptions
css
()
Processes input CSS through synchronous plugins, converts Root
to a CSS string and returns Result#css.
This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error. This is why this method is only for debug purpose, you should always use LazyResult#then.
Type: string
content
()
An alias for the css
property. Use it with syntaxes
that generate non-CSS output.
This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error. This is why this method is only for debug purpose, you should always use LazyResult#then.
Type: string
map
()
Processes input CSS through synchronous plugins and returns Result#map.
This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error. This is why this method is only for debug purpose, you should always use LazyResult#then.
Type: SourceMapGenerator
root
()
Processes input CSS through synchronous plugins and returns Result#root.
This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
This is why this method is only for debug purpose, you should always use LazyResult#then.
Type: Root
messages
()
Processes input CSS through synchronous plugins and returns Result#messages.
This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
This is why this method is only for debug purpose, you should always use LazyResult#then.
warnings
()
Processes input CSS through synchronous plugins and calls Result#warnings().
Array<Warning>
:
Warnings from plugins.
toString
()
Alias for the LazyResult#css property.
string
:
Output CSS.
lazy + '' === lazy.css
then
(onFulfilled, onRejected)
Processes input CSS through synchronous and asynchronous plugins
and calls onFulfilled
with a Result instance. If a plugin throws
an error, the onRejected
callback will be executed.
It implements standard Promise API.
parameter | type | description |
---|---|---|
onFulfilled |
onFulfilled | Callback will be executed when all plugins will finish work. |
onRejected |
onRejected | Callback will be executed on any error. |
Promise
:
Promise API to make queue.
postcss([autoprefixer]).process(css, { from: cssPath }).then(result => {
console.log(result.css)
})
catch
(onRejected)
Processes input CSS through synchronous and asynchronous plugins and calls onRejected for each error thrown in any plugin.
It implements standard Promise API.
parameter | type | description |
---|---|---|
onRejected |
onRejected | Callback will be executed on any error. |
Promise
:
Promise API to make queue.
postcss([autoprefixer]).process(css).then(result => {
console.log(result.css)
}).catch(error => {
console.error(error)
})
finally
(onFinally)
Processes input CSS through synchronous and asynchronous plugins and calls onFinally on any error or when all plugins will finish work.
It implements standard Promise API.
parameter | type | description |
---|---|---|
onFinally |
onFinally | Callback will be executed on any error or when all plugins will finish work. |
Promise
:
Promise API to make queue.
postcss([autoprefixer]).process(css).finally(() => {
console.log('processing ended')
})
Node
(defaults = {})
All node classes inherit the following common methods.
parameter | type | description |
---|---|---|
defaults |
object?
= {}
|
Value for node properties. |
error
(message, opts = {})
Returns a CssSyntaxError
instance containing the original position
of the node in the source, showing line and column numbers and also
a small excerpt to facilitate debugging.
If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).
This method produces very useful error messages.
parameter | type | description |
---|---|---|
message |
string | Error description. |
opts |
object?
= {}
|
Options. |
opts.plugin | string | Plugin name that created this error. PostCSS will set it automatically. |
opts.word | string | A word inside a node’s string that should be highlighted as the source of the error. |
opts.index | number | An index inside a node’s string that should be highlighted as the source of the error. |
CssSyntaxError
:
Error object to throw 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
}
warn
(result, text, opts?)
This method is provided as a convenience wrapper for Result#warn.
parameter | type | description |
---|---|---|
result |
Result | The Result instance that will receive the warning. |
text |
string | Warning message. |
opts |
object? | Options |
opts.plugin | string | Plugin name that created this warning. PostCSS will set it automatically. |
opts.word | string | A word inside a node’s string that should be highlighted as the source of the warning. |
opts.index | number | An index inside a node’s string that should be highlighted as the source of the warning. |
Warning
:
Created warning object.
const plugin = postcss.plugin('postcss-deprecated', () => {
return (root, result) => {
root.walkDecls('bad', decl => {
decl.warn(result, 'Deprecated property bad')
})
}
})
remove
()
Removes the node from its parent and cleans the parent properties from the node and its children.
Node
:
Node to make calls chain.
if (decl.prop.match(/^-webkit-/)) {
decl.remove()
}
toString
(stringifier = stringify)
Returns a CSS string representing the node.
parameter | type | description |
---|---|---|
stringifier |
(stringifier | syntax)?
= stringify
|
A syntax to use in string generation. |
string
:
CSS string of this node.
postcss.rule({ selector: 'a' }).toString() //=> "a {}"
clone
(overrides = {})
Returns an exact clone of the node.
The resulting cloned node and its (cloned) children will retain code style properties.
parameter | type | description |
---|---|---|
overrides |
object?
= {}
|
New properties to override in the clone. |
Node
:
Clone of the node.
decl.raws.before //=> "\n "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before //=> "\n "
cloned.toString() //=> -moz-transform: scale(0)
cloneBefore
(overrides = {})
Shortcut to clone the node and insert the resulting cloned node before the current node.
parameter | type | description |
---|---|---|
overrides |
object?
= {}
|
Mew properties to override in the clone. |
Node
:
New node
decl.cloneBefore({ prop: '-moz-' + decl.prop })
cloneAfter
(overrides = {})
Shortcut to clone the node and insert the resulting cloned node after the current node.
parameter | type | description |
---|---|---|
overrides |
object?
= {}
|
New properties to override in the clone. |
Node
:
New node.
replaceWith
(nodes)
Inserts node(s) before the current node and removes the current node.
parameter | type | description |
---|---|---|
nodes |
...Node | Mode(s) to replace current one. |
Node
:
Current node to methods chain.
if (atrule.name === 'mixin') {
atrule.replaceWith(mixinRules[atrule.params])
}
next
()
Returns the next child of the node’s parent.
Returns undefined
if the current node is the last child.
(Node | undefined)
:
Next node.
if (comment.text === 'delete next') {
const next = comment.next()
if (next) {
next.remove()
}
}
prev
()
Returns the previous child of the node’s parent.
Returns undefined
if the current node is the first child.
(Node | undefined)
:
Previous node.
const annotation = decl.prev()
if (annotation.type === 'comment') {
readAnnotation(annotation.text)
}
before
(add)
Insert new node before current node to current node’s parent.
Just alias for node.parent.insertBefore(node, add)
.
parameter | type | description |
---|---|---|
add |
(Node | object | string | Array<Node>) | New node. |
Node
:
This node for methods chain.
decl.before('content: ""')
after
(add)
Insert new node after current node to current node’s parent.
Just alias for node.parent.insertAfter(node, add)
.
parameter | type | description |
---|---|---|
add |
(Node | object | string | Array<Node>) | New node. |
Node
:
This node for methods chain.
decl.after('color: black')
raw
(prop, defaultType?)
Returns a Node#raws value. If the node is missing the code style property (because the node was manually built or cloned), PostCSS will try to autodetect the code style property by looking at other nodes in the tree.
parameter | type | description |
---|---|---|
prop |
string | Name of code style property. |
defaultType |
string? | Name of default value, it can be missed if the value is the same as prop. |
string
:
Code style value.
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') //=> ' '
root
()
Finds the Root instance of the node’s tree.
Root
:
Root parent.
root.nodes[0].nodes[0].root() === root
cleanRaws
(keepBetween?)
Clear the code style properties for the node and its children.
parameter | type | description |
---|---|---|
keepBetween |
boolean? | Keep the raws.between symbols. |
undefined
:
node.raws.before //=> ' '
node.cleanRaws()
node.raws.before //=> undefined
PreviousMap
(css, opts?)
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).
parameter | type | description |
---|---|---|
css |
string | Input CSS source. |
opts |
processOptions? | Processor#process options. |
const root = postcss.parse(css, { from: 'a.sass.css' })
root.input.map //=> PreviousMap
inline
()
Was source map inlined by data-uri to input CSS.
Type: boolean
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.
SourceMapGenerator
:
Object with source map information.
withContent
()
Does source map contains sourcesContent
with input source text.
boolean
:
Is
sourcesContent
present.
Processor
(plugins)
Contains plugins to process CSS. Create one Processor
instance,
initialize its plugins, and then use that instance on numerous CSS files.
parameter | type | description |
---|---|---|
plugins |
(Array<(Plugin | pluginFunction)> | Processor)
= []
|
PostCSS plugins. See Processor#use for plugin format. |
const processor = postcss([autoprefixer, precss])
processor.process(css1).then(result => console.log(result.css))
processor.process(css2).then(result => console.log(result.css))
version
()
Current PostCSS version.
Type: string
if (result.processor.version.split('.')[0] !== '6') {
throw new Error('This plugin works only with PostCSS 6')
}
plugins
()
Plugins added to this processor.
Type: Array<pluginFunction>
const processor = postcss([autoprefixer, precss])
processor.plugins.length //=> 2
use
(plugin)
Adds a plugin to be used as a CSS processor.
PostCSS plugin can be in 4 formats:
postcss
method. PostCSS will use that method
as described in #2.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.
parameter | type | description |
---|---|---|
plugin |
(Plugin | pluginFunction | Processor) | PostCSS plugin or Processor with plugins. |
Processes
:
Current processor to make methods chain.
const processor = postcss()
.use(autoprefixer)
.use(precss)
process
(css, opts = {})
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.
parameter | type | description |
---|---|---|
css |
(string | toString | Result) | 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.
|
opts |
processOptions?
= {}
|
Options. |
LazyResult
:
Promise proxy.
processor.process(css, { from: 'a.css', to: 'a.out.css' })
.then(result => {
console.log(result.css)
})
Result
(processor, root, opts)
Provides the result of the PostCSS transformations.
A Result instance is returned by LazyResult#then or Root#toResult methods.
parameter | type | description |
---|---|---|
processor |
Processor | Processor used for this transformation. |
root |
Root | Root node after all transformations. |
opts |
processOptions | Options from the Processor#process or Root#toResult . |
postcss([autoprefixer]).process(css).then(result => {
console.log(result.css)
})
const result2 = postcss.parse(css).toResult()
processor
()
The Processor instance used for this transformation.
Type: Processor
for (const plugin of result.processor.plugins) {
if (plugin.postcssPlugin === 'postcss-bad') {
throw 'postcss-good is incompatible with postcss-bad'
}
})
messages
()
Contains messages from plugins (e.g., warnings or custom messages). Each message should have type and plugin properties.
postcss.plugin('postcss-min-browser', () => {
return (root, result) => {
const browsers = detectMinBrowsersByCanIUse(root)
result.messages.push({
type: 'min-browser',
plugin: 'postcss-min-browser',
browsers
})
}
})
root
()
Root node after all transformations.
Type: Root
root.toResult().root === root
opts
()
Options from the Processor#process or Root#toResult call that produced this Result instance.
Type: processOptions
root.toResult(opts).opts === opts
css
()
A CSS string representing of Result#root.
Type: string
postcss.parse('a{}').toResult().css //=> "a{}"
map
()
An instance of SourceMapGenerator
class from the source-map
library,
representing changes to the Result#root instance.
Type: SourceMapGenerator
result.map.toJSON() //=> { version: 3, file: 'a.css', … }
if (result.map) {
fs.writeFileSync(result.opts.to + '.map', result.map.toString())
}
toString
()
Returns for @{link Result#css} content.
string
:
String representing of
Result#root
.
result + '' === result.css
warn
(text, opts = {})
Creates an instance of Warning and adds it to Result#messages.
parameter | type | description |
---|---|---|
text |
string | Warning message. |
opts |
Object?
= {}
|
Warning options. |
opts.node | Node | CSS node that caused the warning. |
opts.word | string | Word in CSS source that caused the warning. |
opts.index | number | Index in CSS node string that caused the warning. |
opts.plugin | string | Name of the plugin that created this warning. Result#warn fills this property automatically. |
Warning
:
Created warning.
warnings
()
Returns warnings from plugins. Filters Warning instances from Result#messages.
Array<Warning>
:
Warnings from plugins.
result.warnings().forEach(warn => {
console.warn(warn.toString())
})
content
()
An alias for the Result#css property. Use it with syntaxes that generate non-CSS output.
Type: string
result.css === result.content
Root
(defaults)
Represents a CSS file and contains all its parsed nodes.
parameter | type | description |
---|---|---|
defaults |
any |
const root = postcss.parse('a{color:black} b{z-index:2}')
root.type //=> 'root'
root.nodes.length //=> 2
append
(children)
Inserts new nodes to the end of the container.
parameter | type | description |
---|---|---|
children |
...(Node | object | string | Array<Node>) | New nodes. |
Node
:
This node for methods chain.
const decl1 = postcss.decl({ prop: 'color', value: 'black' })
const decl2 = postcss.decl({ 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')
each
(callback)
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.
parameter | type | description |
---|---|---|
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
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
})
every
(condition)
Returns true
if callback returns true
for all of the container’s children.
parameter | type | description |
---|---|---|
condition |
childCondition | Iterator returns true or false. |
boolean
:
Is every child pass condition.
const noPrefixes = rule.every(i => i.prop[0] !== '-')
first
()
The container’s first child.
Type: Node
rule.first === rules.nodes[0]
index
(child)
Returns a child
’s index within the Container#nodes array.
parameter | type | description |
---|---|---|
child |
Node | Child of the current container. |
number
:
Child index.
rule.index( rule.nodes[2] ) //=> 2
insertAfter
(exist, add)
Insert new node after old node within the container.
parameter | type | description |
---|---|---|
exist |
(Node | number) | Child or child’s index. |
add |
(Node | object | string | Array<Node>) | New node. |
Node
:
This node for methods chain.
insertBefore
(exist, add)
Insert new node before old node within the container.
parameter | type | description |
---|---|---|
exist |
(Node | number) | Child or child’s index. |
add |
(Node | object | string | Array<Node>) | New node. |
Node
:
This node for methods chain.
rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
last
()
The container’s last child.
Type: Node
rule.last === rule.nodes[rule.nodes.length - 1]
on
(event, visitor?, type?)
Add visitor for next PostCSS walk.
Visitor subscribes for events. Each event contain node type (atrule
,
rule
, decl
, comment
) and phase (enter
, exit
) separated with dot.
The default phase is enter
. As result possible events could be like
comment.enter
, decl.exit
or rule
(equal to rule.enter
).
PostCSS will walk through CSS AST and call visitor according current node. Visitor will receive node and node’s index.
parameter | type | description |
---|---|---|
event |
any | |
visitor |
visitor? | Function receives node and index. |
type |
visitingEvent? | The type of the node and phase. |
undefined
:
css.on('decl', (node, index) => {
if (node.prop === 'will-change') {
node.cloneBefore({ prop: 'backface-visibility', value: 'hidden' })
}
})
prepend
(children)
Inserts new nodes to the start of the container.
parameter | type | description |
---|---|---|
children |
...(Node | object | string | Array<Node>) | New nodes. |
Node
:
This node for methods chain.
const decl1 = postcss.decl({ prop: 'color', value: 'black' })
const decl2 = postcss.decl({ 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')
removeAll
()
Removes all children from the container and cleans their parent properties.
Node
:
This node for methods chain.
rule.removeAll()
rule.nodes.length //=> 0
removeChild
(child)
Removes node from the container and cleans the parent properties from the node and its children.
parameter | type | description |
---|---|---|
child |
(Node | number) | Child or child’s index. |
Node
:
This node for methods chain
rule.nodes.length //=> 5
rule.removeChild(decl)
rule.nodes.length //=> 4
decl.parent //=> undefined
replaceValues
(pattern, opts, callback)
Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.
This method is useful if you are using a custom unit or function and need to iterate through all values.
parameter | type | description |
---|---|---|
pattern |
(string | RegExp) | Replace pattern. |
opts |
object | Options to speed up the search. |
opts.props | (string | Array<string>) | An array of property names. |
opts.fast | string | String that’s used to narrow down values and speed up the regexp search. |
callback |
(function | string) | String to replace pattern or callback
that returns a new value. The callback
will receive the same arguments
as those passed to a function parameter
of
String#replace
.
|
Node
:
This node for methods chain.
root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
return 15 * parseInt(string) + 'px'
})
some
(condition)
Returns true
if callback returns true
for (at least) one
of the container’s children.
parameter | type | description |
---|---|---|
condition |
childCondition | Iterator returns true or false. |
boolean
:
Is some child pass condition.
const hasPrefix = rule.some(i => i.prop[0] === '-')
toResult
(opts = {})
Returns a Result instance representing the root’s CSS.
parameter | type | description |
---|---|---|
opts |
processOptions?
= {}
|
Options with only
to
and
map
keys.
|
Result
:
Result with current 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 })
walk
(callback)
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.
parameter | type | description |
---|---|---|
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
root.walk(node => {
// Traverses all descendant nodes.
})
walkAtRules
(name?, callback)
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.
parameter | type | description |
---|---|---|
name |
(string | RegExp)? | String or regular expression to filter at-rules by name. |
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
root.walkAtRules(rule => {
if (isOld(rule.name)) rule.remove()
})
let first = false
root.walkAtRules('charset', rule => {
if (!first) {
first = true
} else {
rule.remove()
}
})
walkComments
(callback)
Traverses the container’s descendant nodes, calling callback for each comment node.
Like Container#each, this method is safe to use if you are mutating arrays during iteration.
parameter | type | description |
---|---|---|
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
root.walkComments(comment => {
comment.remove()
})
walkDecls
(prop?, callback)
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.
Like Container#each, this method is safe to use if you are mutating arrays during iteration.
parameter | type | description |
---|---|---|
prop |
(string | RegExp)? | String or regular expression to filter declarations by property name. |
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
root.walkDecls(decl => {
checkPropertySupport(decl.prop)
})
root.walkDecls('border-radius', decl => {
decl.remove()
})
root.walkDecls(/^background/, decl => {
decl.value = takeFirstColorFromGradient(decl.value)
})
walkRules
(selector?, callback)
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.
parameter | type | description |
---|---|---|
selector |
(string | RegExp)? | String or regular expression to filter rules by selector. |
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
returns
false
if iteration was broke.
const selectors = []
root.walkRules(rule => {
selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
Rule
(defaults)
Represents a CSS rule: a selector followed by a declaration block.
parameter | type | description |
---|---|---|
defaults |
any |
const root = postcss.parse('a{}')
const rule = root.first
rule.type //=> 'rule'
rule.toString() //=> 'a{}'
append
(children)
Inserts new nodes to the end of the container.
parameter | type | description |
---|---|---|
children |
...(Node | object | string | Array<Node>) | New nodes. |
Node
:
This node for methods chain.
const decl1 = postcss.decl({ prop: 'color', value: 'black' })
const decl2 = postcss.decl({ 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')
each
(callback)
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.
parameter | type | description |
---|---|---|
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
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
})
every
(condition)
Returns true
if callback returns true
for all of the container’s children.
parameter | type | description |
---|---|---|
condition |
childCondition | Iterator returns true or false. |
boolean
:
Is every child pass condition.
const noPrefixes = rule.every(i => i.prop[0] !== '-')
first
()
The container’s first child.
Type: Node
rule.first === rules.nodes[0]
index
(child)
Returns a child
’s index within the Container#nodes array.
parameter | type | description |
---|---|---|
child |
Node | Child of the current container. |
number
:
Child index.
rule.index( rule.nodes[2] ) //=> 2
insertAfter
(exist, add)
Insert new node after old node within the container.
parameter | type | description |
---|---|---|
exist |
(Node | number) | Child or child’s index. |
add |
(Node | object | string | Array<Node>) | New node. |
Node
:
This node for methods chain.
insertBefore
(exist, add)
Insert new node before old node within the container.
parameter | type | description |
---|---|---|
exist |
(Node | number) | Child or child’s index. |
add |
(Node | object | string | Array<Node>) | New node. |
Node
:
This node for methods chain.
rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
last
()
The container’s last child.
Type: Node
rule.last === rule.nodes[rule.nodes.length - 1]
prepend
(children)
Inserts new nodes to the start of the container.
parameter | type | description |
---|---|---|
children |
...(Node | object | string | Array<Node>) | New nodes. |
Node
:
This node for methods chain.
const decl1 = postcss.decl({ prop: 'color', value: 'black' })
const decl2 = postcss.decl({ 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')
removeAll
()
Removes all children from the container and cleans their parent properties.
Node
:
This node for methods chain.
rule.removeAll()
rule.nodes.length //=> 0
removeChild
(child)
Removes node from the container and cleans the parent properties from the node and its children.
parameter | type | description |
---|---|---|
child |
(Node | number) | Child or child’s index. |
Node
:
This node for methods chain
rule.nodes.length //=> 5
rule.removeChild(decl)
rule.nodes.length //=> 4
decl.parent //=> undefined
replaceValues
(pattern, opts, callback)
Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.
This method is useful if you are using a custom unit or function and need to iterate through all values.
parameter | type | description |
---|---|---|
pattern |
(string | RegExp) | Replace pattern. |
opts |
object | Options to speed up the search. |
opts.props | (string | Array<string>) | An array of property names. |
opts.fast | string | String that’s used to narrow down values and speed up the regexp search. |
callback |
(function | string) | String to replace pattern or callback
that returns a new value. The callback
will receive the same arguments
as those passed to a function parameter
of
String#replace
.
|
Node
:
This node for methods chain.
root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
return 15 * parseInt(string) + 'px'
})
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'
some
(condition)
Returns true
if callback returns true
for (at least) one
of the container’s children.
parameter | type | description |
---|---|---|
condition |
childCondition | Iterator returns true or false. |
boolean
:
Is some child pass condition.
const hasPrefix = rule.some(i => i.prop[0] === '-')
walk
(callback)
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.
parameter | type | description |
---|---|---|
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
root.walk(node => {
// Traverses all descendant nodes.
})
walkAtRules
(name?, callback)
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.
parameter | type | description |
---|---|---|
name |
(string | RegExp)? | String or regular expression to filter at-rules by name. |
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
root.walkAtRules(rule => {
if (isOld(rule.name)) rule.remove()
})
let first = false
root.walkAtRules('charset', rule => {
if (!first) {
first = true
} else {
rule.remove()
}
})
walkComments
(callback)
Traverses the container’s descendant nodes, calling callback for each comment node.
Like Container#each, this method is safe to use if you are mutating arrays during iteration.
parameter | type | description |
---|---|---|
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
root.walkComments(comment => {
comment.remove()
})
walkDecls
(prop?, callback)
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.
Like Container#each, this method is safe to use if you are mutating arrays during iteration.
parameter | type | description |
---|---|---|
prop |
(string | RegExp)? | String or regular expression to filter declarations by property name. |
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
Returns
false
if iteration was broke.
root.walkDecls(decl => {
checkPropertySupport(decl.prop)
})
root.walkDecls('border-radius', decl => {
decl.remove()
})
root.walkDecls(/^background/, decl => {
decl.value = takeFirstColorFromGradient(decl.value)
})
walkRules
(selector?, callback)
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.
parameter | type | description |
---|---|---|
selector |
(string | RegExp)? | String or regular expression to filter rules by selector. |
callback |
childIterator | Iterator receives each node and index. |
(false
| undefined)
:
returns
false
if iteration was broke.
const selectors = []
root.walkRules(rule => {
selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
Warning
(text, opts = {})
Represents a plugin’s warning. It can be created using Node#warn.
parameter | type | description |
---|---|---|
text |
string | Warning message. |
opts |
Object?
= {}
|
Warning options. |
if (decl.important) {
decl.warn(result, 'Avoid !important', { word: '!important' })
}
type
()
Type to filter warnings from Result#messages.
Always equal to "warning"
.
Type: string
const nonWarning = result.messages.filter(i => i.type !== 'warning')
text
()
The warning message.
Type: string
warning.text //=> 'Try to avoid !important'
line
()
Line in the input file with this warning’s source.
Type: number
warning.line //=> 5
column
()
Column in the input file with this warning’s source.
Type: number
warning.column //=> 6
toString
()
Returns a warning position and message.
string
:
Warning position and message.
warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'
list
()
Contains helpers for safely splitting lists of CSS values, preserving parentheses and quotes.
const list = postcss.list
space
(string)
Safely splits space-separated values (such as those for background
,
border-radius
, and other shorthand properties).
parameter | type | description |
---|---|---|
string |
string | Space-separated values. |
Array<string>
:
Split values.
postcss.list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
comma
(string)
Safely splits comma-separated values (such as those for transition-*
and background
properties).
parameter | type | description |
---|---|---|
string |
string | Comma-separated values. |
Array<string>
:
Split values.
postcss.list.comma('black, linear-gradient(white, black)')
//=> ['black', 'linear-gradient(white, black)']
postcss
(plugins)
Create a new Processor instance that will apply plugins
as CSS processors.
parameter | type | description |
---|---|---|
plugins |
(Array<(Plugin | pluginFunction)> | Processor) | PostCSS plugins. See Processor#use for plugin format. |
Processor
:
Processor to process multiple CSS.
let postcss = require('postcss')
postcss(plugins).process(css, { from, to }).then(result => {
console.log(result.css)
})
plugin
(name, initializer)
Creates a PostCSS plugin with a standard API.
The newly-wrapped function will provide both the name and PostCSS version of the plugin.
const processor = postcss([replace])
processor.plugins[0].postcssPlugin //=> 'postcss-replace'
processor.plugins[0].postcssVersion //=> '6.0.0'
The plugin function receives 2 arguments: Root
and Result instance. The function should mutate the provided
Root
node. Alternatively, you can create a new Root
node
and override the result.root
property.
const cleaner = postcss.plugin('postcss-cleaner', () => {
return (root, result) => {
result.root = postcss.root()
}
})
As a convenience, plugins also expose a process
method so that you can use
them as standalone tools.
cleaner.process(css, processOpts, pluginOpts)
// This is equivalent to:
postcss([ cleaner(pluginOpts) ]).process(css, processOpts)
Asynchronous plugins should return a Promise
instance.
postcss.plugin('postcss-import', () => {
return (root, result) => {
return new Promise( (resolve, reject) => {
fs.readFile('base.css', (base) => {
root.prepend(base)
resolve()
})
})
}
})
Add warnings using the Node#warn method. Send data to other plugins using the Result#messages array.
postcss.plugin('postcss-caniuse-test', () => {
return (root, result) => {
root.walkDecls(decl => {
if (!caniuse.support(decl.prop)) {
decl.warn(result, 'Some browsers do not support ' + decl.prop)
}
})
}
})
parameter | type | description |
---|---|---|
name |
string | PostCSS plugin name. Same as in
name
property in
package.json
. It will be saved
in
plugin.postcssPlugin
property.
|
initializer |
function | Will receive plugin options and should return pluginFunction |
Plugin
:
PostCSS plugin.
stringify
(node, builder)
Default function to convert a node tree into a CSS string.
parameter | type | description |
---|---|---|
node |
Node | Start node for stringifing. Usually Root . |
builder |
builder | Function to concatenate CSS from node’s parts or generate string and source map. |
void
:
parse
(css, opts?)
Parses source css and returns a new Root node, which contains the source CSS nodes.
parameter | type | description |
---|---|---|
css |
(string | toString) | String with input CSS or any object with toString() method, like a Buffer |
opts |
processOptions? | Options with only
from
and
map
keys.
|
Root
:
PostCSS AST.
// 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
vendor
()
Contains the vendor module.
Type: vendor
postcss.vendor.unprefixed('-moz-tab') //=> ['tab']
list
()
Contains the list module.
Type: list
postcss.list.space('5px calc(10% + 5px)') //=> ['5px', 'calc(10% + 5px)']
comment
(defaults?)
Creates a new Comment node.
parameter | type | description |
---|---|---|
defaults |
object? | Properties for the new node. |
Comment
:
New comment node
postcss.comment({ text: 'test' })
atRule
(defaults?)
Creates a new AtRule node.
parameter | type | description |
---|---|---|
defaults |
object? | Properties for the new node. |
AtRule
:
new at-rule node
postcss.atRule({ name: 'charset' }).toString() //=> "@charset"
decl
(defaults?)
Creates a new Declaration node.
parameter | type | description |
---|---|---|
defaults |
object? | Properties for the new node. |
Declaration
:
new declaration node
postcss.decl({ prop: 'color', value: 'red' }).toString() //=> "color: red"
rule
(defaults?)
Creates a new Rule node.
parameter | type | description |
---|---|---|
defaults |
object? | Properties for the new node. |
Rule
:
new rule node
postcss.rule({ selector: 'a' }).toString() //=> "a {\n}"
root
(defaults?)
Creates a new Root node.
parameter | type | description |
---|---|---|
defaults |
object? | Properties for the new node. |
Root
:
new root node.
postcss.root({ after: '\n' }).toString() //=> "\n"
vendor
()
Contains helpers for working with vendor prefixes.
const vendor = postcss.vendor
prefix
(prop)
Returns the vendor prefix extracted from an input string.
parameter | type | description |
---|---|---|
prop |
string | String with or without vendor prefix. |
string
:
vendor prefix or empty string
postcss.vendor.prefix('-moz-tab-size') //=> '-moz-'
postcss.vendor.prefix('tab-size') //=> ''
unprefixed
(prop)
Returns the input string stripped of its vendor prefix.
parameter | type | description |
---|---|---|
prop |
string | String with or without vendor prefix. |
string
:
String name without vendor prefixes.
postcss.vendor.unprefixed('-moz-tab-size') //=> 'tab-size'
Message
()
Type: object
property | type | description |
---|---|---|
type | string | : Message type. |
plugin | string | : Source PostCSS plugin name. |
Plugin
()
Type: object
property | type | description |
---|---|---|
postcss | function | : PostCSS plugin function. |
builder
(part, node, type?)
Type: Function
parameter | type | description |
---|---|---|
part |
string | Part of generated CSS connected to this node. |
node |
Node | AST node. |
type |
("start" | "end" )?
|
Node’s part type. |
childCondition
(node, index, nodes)
Type: Function
parameter | type | description |
---|---|---|
node |
Node | Container child. |
index |
number | Child index. |
nodes |
Array<Node> | All container children. |
boolean
:
childIterator
(node, index)
Type: Function
parameter | type | description |
---|---|---|
node |
Node | Container child. |
index |
number | Child index. |
(false
| undefined)
:
Returning
false
will break iteration.
filePosition
()
Type: object
property | type | description |
---|---|---|
file | string | : Path to file. |
line | number | : Source line in file. |
column | number | : Source column in file. |
onFulfilled
(result)
Type: Function
parameter | type | description |
---|---|---|
result |
Result |
onRejected
(error)
Type: Function
parameter | type | description |
---|---|---|
error |
Error |
parser
(css, opts?)
Type: Function
parameter | type | description |
---|---|---|
css |
(string | toString) | String with input CSS or any object with toString() method, like a Buffer. |
opts |
processOptions? | Options with only
from
and
map
keys.
|
Root
:
PostCSS AST
pluginFunction
(root, result)
Type: Function
parameter | type | description |
---|---|---|
root |
Root | Parsed input CSS. |
result |
Result | Result to set warnings or check other plugins. |
position
()
Type: object
property | type | description |
---|---|---|
line | number | : Source line in file. |
column | number | : Source column in file. |
processOptions
()
Type: object
property | type | description |
---|---|---|
from | string | : The path of the CSS source file.
You should always set
from
,
because it is used in source map
generation and syntax error messages.
|
to | string | : The path where you’ll put the output
CSS file. You should always set
to
to generate correct source maps.
|
parser | parser | : Function to generate AST by string. |
stringifier | stringifier | : Class to generate string by AST. |
syntax | syntax | : Object with
parse
and
stringify
.
|
map | object | : Source map options. |
map | object | : Source map options. |
source
()
Type: object
property | type | description |
---|---|---|
input | Input | : Input with input file |
start | position | : The starting position of the node’s source. |
end | position | : The ending position of the node’s source. |
stringifier
(node, builder)
Type: Function
parameter | type | description |
---|---|---|
node |
Node | Start node for stringifing. Usually Root . |
builder |
builder | Function to concatenate CSS from node’s parts or generate string and source map. |
void
:
syntax
()
Type: object
property | type | description |
---|---|---|
parse | parser | : Function to generate AST by string. |
stringify | stringifier | : Function to generate string by AST. |
toString
()
Type: object
property | type | description |
---|---|---|
toString | function |
visitor
(node, index)
Type: Function
parameter | type | description |
---|---|---|
node |
Node | Container child. |
index |
number | Child index. |