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)
})
Argument | Type | Description |
---|---|---|
plugins | AcceptedPlugin[] | PostCSS plugins. |
Argument | Type | Description |
---|---|---|
plugins… | AcceptedPlugin[] | PostCSS plugins. |
Returns default
. Processor to process multiple CSS.
postcss.AtRule
Type: typeof default.
postcss.Comment
Type: typeof default.
postcss.Container
Type: typeof default.
postcss.CssSyntaxError
Type: typeof default.
postcss.Declaration
Type: typeof default.
postcss.Input
Type: typeof default.
postcss.Node
Type: typeof default.
postcss.Result
Type: typeof default.
postcss.Root
Type: typeof default.
postcss.Rule
Type: typeof default.
postcss.Warning
Type: typeof default.
postcss.fromJSON
Rehydrate a JSON AST (from Node#toJSON
) back into the AST classes.
const json = root.toJSON()
// save to file, send by network, etc
const root2 = postcss.fromJSON(json)
Type: JSONHydrator.
postcss.list
Contains the list
module.
Type: List.
postcss.parse
Parses source css and returns a new Root
or Document
node,
which contains the source CSS nodes.
// Simple CSS concatenation with source map support
const root1 = postcss.parse(css1, { from: file1 })
const root2 = postcss.parse(css2, { from: file2 })
root1.append(root2).toResult().css
Type: Parser<default>.
postcss.stringify
Default function to convert a node tree into a CSS string.
Type: Stringifier.
postcss.atRule()
Creates a new AtRule
node.
Argument | Type | Description |
---|---|---|
defaults | AtRuleProps | Properties for the new node. |
Returns default
. New at-rule node.
postcss.comment()
Creates a new Comment
node.
Argument | Type | Description |
---|---|---|
defaults | CommentProps | Properties for the new node. |
Returns default
. New comment node
postcss.decl()
Creates a new Declaration
node.
Argument | Type | Description |
---|---|---|
defaults | DeclarationProps | Properties for the new node. |
Returns default
. New declaration node.
postcss.document()
Creates a new Document
node.
Argument | Type | Description |
---|---|---|
defaults | DocumentProps | Properties for the new node. |
Returns default
. New document node.
postcss.root()
Creates a new Root
node.
Argument | Type | Description |
---|---|---|
defaults | RootProps | Properties for the new node. |
Returns default
. New root node.
postcss.rule()
Creates a new Rule
node.
Argument | Type |
---|---|
defaults | RuleProps |
Returns default
. New rule node.
AtRule
Represents an at-rule.
Once (root, { AtRule }) {
let media = new AtRule({ name: 'media', params: 'print' })
media.append(…)
root.append(media)
}
If it’s followed in the CSS by a {} block, this node will have a nodes property representing its children.
const root = postcss.parse('@charset "UTF-8"; @media print {}')
const charset = root.first
charset.type //=> 'atrule'
charset.nodes //=> undefined
const media = root.last
media.nodes //=> []
AtRule#name
The at-rule’s name immediately follows the @
.
const root = postcss.parse('@media print {}')
media.name //=> 'media'
const media = root.first
Type: string.
AtRule#nodes
An array containing the container’s children.
const root = postcss.parse('a { color: black }')
root.nodes.length //=> 1
root.nodes[0].selector //=> 'a'
root.nodes[0].nodes[0].prop //=> 'color'
Type: ChildNode[].
AtRule#params
The at-rule’s parameters, the values that follow the at-rule’s name but precede any {} block.
const root = postcss.parse('@media print, screen {}')
const media = root.first
media.params //=> 'print, screen'
Type: string.
AtRule#parent
The node’s parent node.
root.nodes[0].parent === root
Type: default<ChildNode>.
AtRule#raws
Information to generate byte-to-byte equal node string as it was in the origin input.
Every parser saves its own properties, but the default CSS parser uses:
before
: the space symbols before the node. It also stores*
and_
symbols before the declaration (IE hack).after
: the space symbols after the last child of the node to the end of the node.between
: the symbols between the property and value for declarations, selector and{
for rules, or last parameter and{
for at-rules.semicolon
: contains true if the last child has an (optional) semicolon.afterName
: the space between the at-rule name and its parameters.left
: the space symbols between/*
and the comment’s text.right
: the space symbols between the comment’s text and */.important
: the content of the important statement, if it is not just!important
.
PostCSS cleans selectors, declaration values and at-rule parameters from comments and extra spaces, but it stores origin content in raws properties. As such, if you don’t change a declaration’s value, PostCSS will use the raw value with comments.
const root = postcss.parse('a {\n color:black\n}')
root.first.first.raws //=> { before: '\n ', between: ':' }
Type: AtRuleRaws.
AtRule#source
The input source of the node.
The property is used in source map generation.
If you create a node manually (e.g., with postcss.decl()
),
that node will not have a source
property and will be absent
from the source map. For this reason, the plugin developer should
consider cloning nodes to create new ones (in which case the new node’s
source will reference the original, cloned node) or setting
the source
property manually.
decl.source.input.from //=> '/home/ai/a.sass'
decl.source.start //=> { line: 10, column: 2 }
decl.source.end //=> { line: 10, column: 12 }
// Bad
const prefixed = postcss.decl({
prop: '-moz-' + decl.prop,
value: decl.value
})
// Good
const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
if (atrule.name === 'add-link') {
const rule = postcss.rule({ selector: 'a', source: atrule.source })
atrule.parent.insertBefore(atrule, rule)
}
Type: Source.
AtRule#type
tring representing the node’s type. Possible values are root
, atrule
,
rule
, decl
, or comment
.
new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
Type: "atrule".
AtRule#first
The container’s first child.
rule.first === rules.nodes[0]
AtRule#last
The container’s last child.
rule.last === rule.nodes[rule.nodes.length - 1]
AtRule#after()
Insert new node after current node to current node’s parent.
Just alias for node.parent.insertAfter(node, add)
.
decl.after('color: black')
Argument | Type | Description |
---|---|---|
newNode | string | ChildProps | default | default[] | New node. |
Returns default
. This node for methods chain.
AtRule#append()
Inserts new nodes to the end of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.append(decl1, decl2)
root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
root.append({ selector: 'a' }) // rule
rule.append({ prop: 'color', value: 'black' }) // declaration
rule.append({ text: 'Comment' }) // comment
root.append('a {}')
root.first.append('color: black; z-index: 1')
Argument | Type | Description |
---|---|---|
nodes… | (string | ChildProps | default | default[] | ChildProps[] | string[])[] | New nodes. |
Returns default
. This node for methods chain.
AtRule#assign()
Assigns properties to the current node.
decl.assign({ prop: 'word-wrap', value: 'break-word' })
Argument | Type | Description |
---|---|---|
overrides | object | AtRuleProps | New properties to override the node. |
Returns default
. Current node to methods chain.
AtRule#before()
Insert new node before current node to current node’s parent.
Just alias for node.parent.insertBefore(node, add)
.
decl.before('content: ""')
Argument | Type | Description |
---|---|---|
newNode | string | ChildProps | default | default[] | New node. |
Returns default
. This node for methods chain.
AtRule#cleanRaws()
Clear the code style properties for the node and its children.
node.raws.before //=> ' '
node.cleanRaws()
node.raws.before //=> undefined
Argument | Type | Description |
---|---|---|
keepBetween | boolean | Keep the raws.between symbols. |
AtRule#clone()
Returns an exact clone of the node.
The resulting cloned node and its (cloned) children will retain code style properties.
decl.raws.before //=> "\n "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before //=> "\n "
cloned.toString() //=> -moz-transform: scale(0)
Argument | Type | Description |
---|---|---|
overrides | Partial<AtRuleProps> | New properties to override in the clone. |
Returns default
. Clone of the node.
AtRule#cloneAfter()
Shortcut to clone the node and insert the resulting cloned node after the current node.
Argument | Type | Description |
---|---|---|
overrides | Partial<AtRuleProps> | New properties to override in the clone. |
Returns default
. New node.
AtRule#cloneBefore()
Shortcut to clone the node and insert the resulting cloned node before the current node.
decl.cloneBefore({ prop: '-moz-' + decl.prop })
Argument | Type | Description |
---|---|---|
overrides | Partial<AtRuleProps> | Mew properties to override in the clone. |
Returns default
. New node
AtRule#each()
Iterates through the container’s immediate children,
calling callback
for each child.
Returning false
in the callback will break iteration.
This method only iterates through the container’s immediate children.
If you need to recursively iterate through all the container’s descendant
nodes, use Container#walk
.
Unlike the for {}
-cycle or Array#forEach
this iterator is safe
if you are mutating the array of child nodes during iteration.
PostCSS will adjust the current index to match the mutations.
const root = postcss.parse('a { color: black; z-index: 1 }')
const rule = root.first
for (const decl of rule.nodes) {
decl.cloneBefore({ prop: '-webkit-' + decl.prop })
// Cycle will be infinite, because cloneBefore moves the current node
// to the next index
}
rule.each(decl => {
decl.cloneBefore({ prop: '-webkit-' + decl.prop })
// Will be executed only for color and z-index
})
Argument | Type | Description |
---|---|---|
callback | (node: ChildNode, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
AtRule#error()
Returns a CssSyntaxError
instance containing the original position
of the node in the source, showing line and column numbers and also
a small excerpt to facilitate debugging.
If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).
This method produces very useful error messages.
if (!variables[name]) {
throw decl.error(`Unknown variable ${name}`, { word: name })
// CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
// color: $black
// a
// ^
// background: white
}
Argument | Type | Description |
---|---|---|
message | string | Error description. |
options | NodeErrorOptions |
Returns default
. Error object to throw it.
AtRule#every()
Returns true
if callback returns true
for all of the container’s children.
const noPrefixes = rule.every(i => i.prop[0] !== '-')
Argument | Type | Description |
---|---|---|
condition | (node: ChildNode, index: number, nodes: ChildNode[]) => boolean | Iterator returns true or false. |
Returns boolean
. Is every child pass condition.
AtRule#index()
Returns a child
’s index within the Container#nodes
array.
rule.index( rule.nodes[2] ) //=> 2
Argument | Type | Description |
---|---|---|
child | number | ChildNode | Child of the current container. |
Returns number
. Child index.
AtRule#insertAfter()
Insert new node after old node within the container.
Argument | Type | Description |
---|---|---|
oldNode | number | ChildNode | Child or child’s index. |
newNode | string | ChildNode | ChildProps | ChildNode[] | ChildProps[] | string[] | New node. |
Returns default
. This node for methods chain.
AtRule#insertBefore()
Insert new node before old node within the container.
rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
Argument | Type | Description |
---|---|---|
oldNode | number | ChildNode | Child or child’s index. |
newNode | string | ChildNode | ChildProps | ChildNode[] | ChildProps[] | string[] | New node. |
Returns default
. This node for methods chain.
AtRule#next()
Returns the next child of the node’s parent.
Returns undefined
if the current node is the last child.
if (comment.text === 'delete next') {
const next = comment.next()
if (next) {
next.remove()
}
}
Argument | Type |
---|
Returns ChildNode
. Next node.
AtRule#positionBy()
Get the position for a word or an index inside the node.
Argument | Type | Description |
---|---|---|
opts | Pick<WarningOptions, "word" | "index"> | Options. |
Returns Position
. Position.
AtRule#positionInside()
Convert string index to line/column.
Argument | Type | Description |
---|---|---|
index | number | The symbol number in the node’s string. |
Returns Position
. Symbol position in file.
AtRule#prepend()
Inserts new nodes to the start of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.prepend(decl1, decl2)
root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
root.append({ selector: 'a' }) // rule
rule.append({ prop: 'color', value: 'black' }) // declaration
rule.append({ text: 'Comment' }) // comment
root.append('a {}')
root.first.append('color: black; z-index: 1')
Argument | Type | Description |
---|---|---|
nodes… | (string | ChildProps | default | default[] | ChildProps[] | string[])[] | New nodes. |
Returns default
. This node for methods chain.
AtRule#prev()
Returns the previous child of the node’s parent.
Returns undefined
if the current node is the first child.
const annotation = decl.prev()
if (annotation.type === 'comment') {
readAnnotation(annotation.text)
}
Argument | Type |
---|
Returns ChildNode
. Previous node.
AtRule#push()
Add child to the end of the node.
rule.push(new Declaration({ prop: 'color', value: 'black' }))
Argument | Type | Description |
---|---|---|
child | ChildNode | New node. |
Returns default
. This node for methods chain.
AtRule#rangeBy()
Get the range for a word or start and end index inside the node. The start index is inclusive; the end index is exclusive.
Argument | Type | Description |
---|---|---|
opts | Pick<WarningOptions, "word" | "index" | "endIndex"> | Options. |
Returns Range
. Range.
AtRule#raw()
Returns a Node#raws
value. If the node is missing
the code style property (because the node was manually built or cloned),
PostCSS will try to autodetect the code style property by looking
at other nodes in the tree.
const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
Argument | 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. |
Returns string
. Code style value.
AtRule#remove()
Removes the node from its parent and cleans the parent properties from the node and its children.
if (decl.prop.match(/^-webkit-/)) {
decl.remove()
}
Argument | Type |
---|
Returns default
. Node to make calls chain.
AtRule#removeAll()
Removes all children from the container and cleans their parent properties.
rule.removeAll()
rule.nodes.length //=> 0
Argument | Type |
---|
Returns default
. This node for methods chain.
AtRule#removeChild()
Removes node from the container and cleans the parent properties from the node and its children.
rule.nodes.length //=> 5
rule.removeChild(decl)
rule.nodes.length //=> 4
decl.parent //=> undefined
Argument | Type | Description |
---|---|---|
child | number | ChildNode | Child or child’s index. |
Returns default
. This node for methods chain.
AtRule#replaceValues()
Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.
This method is useful if you are using a custom unit or function and need to iterate through all values.
root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
return 15 * parseInt(string) + 'px'
})
Argument | Type | Description |
---|---|---|
pattern | string | RegExp | Replace pattern. |
options | ValueOptions | |
replaced | string | (substring: string, args: any[]) => string |
Argument | Type | Description |
---|---|---|
pattern | string | RegExp | Replace pattern. |
replaced | string | (substring: string, args: any[]) => string |
Returns default
. This node for methods chain.
AtRule#replaceWith()
Inserts node(s) before the current node and removes the current node.
AtRule: {
mixin: atrule => {
atrule.replaceWith(mixinRules[atrule.params])
}
}
Argument | Type | Description |
---|---|---|
nodes… | (ChildNode | ChildProps | ChildNode[] | ChildProps[])[] | Mode(s) to replace current one. |
Returns default
. Current node to methods chain.
AtRule#root()
Finds the Root instance of the node’s tree.
root.nodes[0].nodes[0].root() === root
Argument | Type |
---|
Returns default
. Root parent.
AtRule#some()
Returns true
if callback returns true
for (at least) one
of the container’s children.
const hasPrefix = rule.some(i => i.prop[0] === '-')
Argument | Type | Description |
---|---|---|
condition | (node: ChildNode, index: number, nodes: ChildNode[]) => boolean | Iterator returns true or false. |
Returns boolean
. Is some child pass condition.
AtRule#toJSON()
Fix circular links on JSON.stringify()
.
Argument | Type |
---|
Returns object
. Cleaned object.
AtRule#toString()
Returns a CSS string representing the node.
new Rule({ selector: 'a' }).toString() //=> "a {}"
Argument | Type | Description |
---|---|---|
stringifier | Stringifier | Syntax | A syntax to use in string generation. |
Returns string
. CSS string of this node.
AtRule#walk()
Traverses the container’s descendant nodes, calling callback for each node.
Like container.each(), this method is safe to use if you are mutating arrays during iteration.
If you only need to iterate through the container’s immediate children,
use Container#each
.
root.walk(node => {
// Traverses all descendant nodes.
})
Argument | Type | Description |
---|---|---|
callback | (node: ChildNode, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
AtRule#walkAtRules()
Traverses the container’s descendant nodes, calling callback for each at-rule node.
If you pass a filter, iteration will only happen over at-rules that have matching names.
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
root.walkAtRules(rule => {
if (isOld(rule.name)) rule.remove()
})
let first = false
root.walkAtRules('charset', rule => {
if (!first) {
first = true
} else {
rule.remove()
}
})
Argument | Type | Description |
---|---|---|
nameFilter | string | RegExp | |
callback | (atRule: default, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
AtRule#walkComments()
Traverses the container’s descendant nodes, calling callback for each comment node.
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
root.walkComments(comment => {
comment.remove()
})
Argument | Type | Description |
---|---|---|
callback | (comment: default, indexed: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
AtRule#walkDecls()
Traverses the container’s descendant nodes, calling callback for each declaration node.
If you pass a filter, iteration will only happen over declarations with matching properties.
root.walkDecls(decl => {
checkPropertySupport(decl.prop)
})
root.walkDecls('border-radius', decl => {
decl.remove()
})
root.walkDecls(/^background/, decl => {
decl.value = takeFirstColorFromGradient(decl.value)
})
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
Argument | Type | Description |
---|---|---|
propFilter | string | RegExp | |
callback | (decl: default, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
AtRule#walkRules()
Traverses the container’s descendant nodes, calling callback for each rule node.
If you pass a filter, iteration will only happen over rules with matching selectors.
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
const selectors = []
root.walkRules(rule => {
selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
Argument | Type | Description |
---|---|---|
selectorFilter | string | RegExp | |
callback | (rule: default, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
AtRule#warn()
This method is provided as a convenience wrapper for Result#warn
.
Declaration: {
bad: (decl, { result }) => {
decl.warn(result, 'Deprecated property bad')
}
}
Argument | Type | Description |
---|---|---|
result | default | The Result instance that will receive the warning. |
text | string | Warning message. |
opts | WarningOptions | Warning Options. |
Returns default
. Created warning object.
Comment
Represents a comment between declarations or statements (rule and at-rules).
Once (root, { Comment }) {
let note = new Comment({ text: 'Note: …' })
root.append(note)
}
Comments inside selectors, at-rule parameters, or declaration values
will be stored in the raws
properties explained above.
Comment#parent
The node’s parent node.
root.nodes[0].parent === root
Type: default<ChildNode>.
Comment#raws
Information to generate byte-to-byte equal node string as it was in the origin input.
Every parser saves its own properties, but the default CSS parser uses:
before
: the space symbols before the node. It also stores*
and_
symbols before the declaration (IE hack).after
: the space symbols after the last child of the node to the end of the node.between
: the symbols between the property and value for declarations, selector and{
for rules, or last parameter and{
for at-rules.semicolon
: contains true if the last child has an (optional) semicolon.afterName
: the space between the at-rule name and its parameters.left
: the space symbols between/*
and the comment’s text.right
: the space symbols between the comment’s text and */.important
: the content of the important statement, if it is not just!important
.
PostCSS cleans selectors, declaration values and at-rule parameters from comments and extra spaces, but it stores origin content in raws properties. As such, if you don’t change a declaration’s value, PostCSS will use the raw value with comments.
const root = postcss.parse('a {\n color:black\n}')
root.first.first.raws //=> { before: '\n ', between: ':' }
Type: CommentRaws.
Comment#source
The input source of the node.
The property is used in source map generation.
If you create a node manually (e.g., with postcss.decl()
),
that node will not have a source
property and will be absent
from the source map. For this reason, the plugin developer should
consider cloning nodes to create new ones (in which case the new node’s
source will reference the original, cloned node) or setting
the source
property manually.
decl.source.input.from //=> '/home/ai/a.sass'
decl.source.start //=> { line: 10, column: 2 }
decl.source.end //=> { line: 10, column: 12 }
// Bad
const prefixed = postcss.decl({
prop: '-moz-' + decl.prop,
value: decl.value
})
// Good
const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
if (atrule.name === 'add-link') {
const rule = postcss.rule({ selector: 'a', source: atrule.source })
atrule.parent.insertBefore(atrule, rule)
}
Type: Source.
Comment#text
The comment's text.
Type: string.
Comment#type
tring representing the node’s type. Possible values are root
, atrule
,
rule
, decl
, or comment
.
new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
Type: "comment".
Comment#after()
Insert new node after current node to current node’s parent.
Just alias for node.parent.insertAfter(node, add)
.
decl.after('color: black')
Argument | Type | Description |
---|---|---|
newNode | string | ChildProps | default | default[] | New node. |
Returns default
. This node for methods chain.
Comment#assign()
Assigns properties to the current node.
decl.assign({ prop: 'word-wrap', value: 'break-word' })
Argument | Type | Description |
---|---|---|
overrides | object | CommentProps | New properties to override the node. |
Returns default
.
Comment#before()
Insert new node before current node to current node’s parent.
Just alias for node.parent.insertBefore(node, add)
.
decl.before('content: ""')
Argument | Type | Description |
---|---|---|
newNode | string | ChildProps | default | default[] | New node. |
Returns default
. This node for methods chain.
Comment#cleanRaws()
Clear the code style properties for the node and its children.
node.raws.before //=> ' '
node.cleanRaws()
node.raws.before //=> undefined
Argument | Type | Description |
---|---|---|
keepBetween | boolean | Keep the raws.between symbols. |
Comment#clone()
Returns an exact clone of the node.
The resulting cloned node and its (cloned) children will retain code style properties.
decl.raws.before //=> "\n "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before //=> "\n "
cloned.toString() //=> -moz-transform: scale(0)
Argument | Type | Description |
---|---|---|
overrides | Partial<CommentProps> | New properties to override in the clone. |
Returns default
.
Comment#cloneAfter()
Shortcut to clone the node and insert the resulting cloned node after the current node.
Argument | Type | Description |
---|---|---|
overrides | Partial<CommentProps> | New properties to override in the clone. |
Returns default
.
Comment#cloneBefore()
Shortcut to clone the node and insert the resulting cloned node before the current node.
decl.cloneBefore({ prop: '-moz-' + decl.prop })
Argument | Type | Description |
---|---|---|
overrides | Partial<CommentProps> | Mew properties to override in the clone. |
Returns default
.
Comment#error()
Returns a CssSyntaxError
instance containing the original position
of the node in the source, showing line and column numbers and also
a small excerpt to facilitate debugging.
If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).
This method produces very useful error messages.
if (!variables[name]) {
throw decl.error(`Unknown variable ${name}`, { word: name })
// CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
// color: $black
// a
// ^
// background: white
}
Argument | Type | Description |
---|---|---|
message | string | Error description. |
options | NodeErrorOptions |
Returns default
. Error object to throw it.
Comment#next()
Returns the next child of the node’s parent.
Returns undefined
if the current node is the last child.
if (comment.text === 'delete next') {
const next = comment.next()
if (next) {
next.remove()
}
}
Argument | Type |
---|
Returns ChildNode
. Next node.
Comment#positionBy()
Get the position for a word or an index inside the node.
Argument | Type | Description |
---|---|---|
opts | Pick<WarningOptions, "word" | "index"> | Options. |
Returns Position
. Position.
Comment#positionInside()
Convert string index to line/column.
Argument | Type | Description |
---|---|---|
index | number | The symbol number in the node’s string. |
Returns Position
. Symbol position in file.
Comment#prev()
Returns the previous child of the node’s parent.
Returns undefined
if the current node is the first child.
const annotation = decl.prev()
if (annotation.type === 'comment') {
readAnnotation(annotation.text)
}
Argument | Type |
---|
Returns ChildNode
. Previous node.
Comment#rangeBy()
Get the range for a word or start and end index inside the node. The start index is inclusive; the end index is exclusive.
Argument | Type | Description |
---|---|---|
opts | Pick<WarningOptions, "word" | "index" | "endIndex"> | Options. |
Returns Range
. Range.
Comment#raw()
Returns a Node#raws
value. If the node is missing
the code style property (because the node was manually built or cloned),
PostCSS will try to autodetect the code style property by looking
at other nodes in the tree.
const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
Argument | 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. |
Returns string
. Code style value.
Comment#remove()
Removes the node from its parent and cleans the parent properties from the node and its children.
if (decl.prop.match(/^-webkit-/)) {
decl.remove()
}
Argument | Type |
---|
Returns default
. Node to make calls chain.
Comment#replaceWith()
Inserts node(s) before the current node and removes the current node.
AtRule: {
mixin: atrule => {
atrule.replaceWith(mixinRules[atrule.params])
}
}
Argument | Type | Description |
---|---|---|
nodes… | (ChildNode | ChildProps | ChildNode[] | ChildProps[])[] | Mode(s) to replace current one. |
Returns default
. Current node to methods chain.
Comment#root()
Finds the Root instance of the node’s tree.
root.nodes[0].nodes[0].root() === root
Argument | Type |
---|
Returns default
. Root parent.
Comment#toJSON()
Fix circular links on JSON.stringify()
.
Argument | Type |
---|
Returns object
. Cleaned object.
Comment#toString()
Returns a CSS string representing the node.
new Rule({ selector: 'a' }).toString() //=> "a {}"
Argument | Type | Description |
---|---|---|
stringifier | Stringifier | Syntax | A syntax to use in string generation. |
Returns string
. CSS string of this node.
Comment#warn()
This method is provided as a convenience wrapper for Result#warn
.
Declaration: {
bad: (decl, { result }) => {
decl.warn(result, 'Deprecated property bad')
}
}
Argument | Type | Description |
---|---|---|
result | default | The Result instance that will receive the warning. |
text | string | Warning message. |
opts | WarningOptions | Warning Options. |
Returns default
. Created warning object.
Container
The Root
, AtRule
, and Rule
container nodes
inherit some common methods to help work with their children.
Note that all containers can store any content. If you write a rule inside a rule, PostCSS will parse it.
Container#nodes
An array containing the container’s children.
const root = postcss.parse('a { color: black }')
root.nodes.length //=> 1
root.nodes[0].selector //=> 'a'
root.nodes[0].nodes[0].prop //=> 'color'
Type: Child[].
Container#parent
The node’s parent node.
root.nodes[0].parent === root
Type: default<ChildNode> | default.
Container#raws
Information to generate byte-to-byte equal node string as it was in the origin input.
Every parser saves its own properties, but the default CSS parser uses:
before
: the space symbols before the node. It also stores*
and_
symbols before the declaration (IE hack).after
: the space symbols after the last child of the node to the end of the node.between
: the symbols between the property and value for declarations, selector and{
for rules, or last parameter and{
for at-rules.semicolon
: contains true if the last child has an (optional) semicolon.afterName
: the space between the at-rule name and its parameters.left
: the space symbols between/*
and the comment’s text.right
: the space symbols between the comment’s text and */.important
: the content of the important statement, if it is not just!important
.
PostCSS cleans selectors, declaration values and at-rule parameters from comments and extra spaces, but it stores origin content in raws properties. As such, if you don’t change a declaration’s value, PostCSS will use the raw value with comments.
const root = postcss.parse('a {\n color:black\n}')
root.first.first.raws //=> { before: '\n ', between: ':' }
Type: any.
Container#source
The input source of the node.
The property is used in source map generation.
If you create a node manually (e.g., with postcss.decl()
),
that node will not have a source
property and will be absent
from the source map. For this reason, the plugin developer should
consider cloning nodes to create new ones (in which case the new node’s
source will reference the original, cloned node) or setting
the source
property manually.
decl.source.input.from //=> '/home/ai/a.sass'
decl.source.start //=> { line: 10, column: 2 }
decl.source.end //=> { line: 10, column: 12 }
// Bad
const prefixed = postcss.decl({
prop: '-moz-' + decl.prop,
value: decl.value
})
// Good
const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
if (atrule.name === 'add-link') {
const rule = postcss.rule({ selector: 'a', source: atrule.source })
atrule.parent.insertBefore(atrule, rule)
}
Type: Source.
Container#type
tring representing the node’s type. Possible values are root
, atrule
,
rule
, decl
, or comment
.
new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
Type: string.
Container#first
The container’s first child.
rule.first === rules.nodes[0]
Container#last
The container’s last child.
rule.last === rule.nodes[rule.nodes.length - 1]
Container#after()
Insert new node after current node to current node’s parent.
Just alias for node.parent.insertAfter(node, add)
.
decl.after('color: black')
Argument | Type | Description |
---|---|---|
newNode | string | ChildProps | default | default[] | New node. |
Returns default<Child>
. This node for methods chain.
Container#append()
Inserts new nodes to the end of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.append(decl1, decl2)
root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
root.append({ selector: 'a' }) // rule
rule.append({ prop: 'color', value: 'black' }) // declaration
rule.append({ text: 'Comment' }) // comment
root.append('a {}')
root.first.append('color: black; z-index: 1')
Argument | Type | Description |
---|---|---|
nodes… | (string | ChildProps | default | default[] | ChildProps[] | string[])[] | New nodes. |
Returns default<Child>
. This node for methods chain.
Container#assign()
Assigns properties to the current node.
decl.assign({ prop: 'word-wrap', value: 'break-word' })
Argument | Type | Description |
---|---|---|
overrides | object | New properties to override the node. |
Returns default<Child>
. Current node to methods chain.
Container#before()
Insert new node before current node to current node’s parent.
Just alias for node.parent.insertBefore(node, add)
.
decl.before('content: ""')
Argument | Type | Description |
---|---|---|
newNode | string | ChildProps | default | default[] | New node. |
Returns default<Child>
. This node for methods chain.
Container#cleanRaws()
Clear the code style properties for the node and its children.
node.raws.before //=> ' '
node.cleanRaws()
node.raws.before //=> undefined
Argument | Type | Description |
---|---|---|
keepBetween | boolean | Keep the raws.between symbols. |
Container#clone()
Returns an exact clone of the node.
The resulting cloned node and its (cloned) children will retain code style properties.
decl.raws.before //=> "\n "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before //=> "\n "
cloned.toString() //=> -moz-transform: scale(0)
Argument | Type | Description |
---|---|---|
overrides | object | New properties to override in the clone. |
Returns default<Child>
. Clone of the node.
Container#cloneAfter()
Shortcut to clone the node and insert the resulting cloned node after the current node.
Argument | Type | Description |
---|---|---|
overrides | object | New properties to override in the clone. |
Returns default<Child>
. New node.
Container#cloneBefore()
Shortcut to clone the node and insert the resulting cloned node before the current node.
decl.cloneBefore({ prop: '-moz-' + decl.prop })
Argument | Type | Description |
---|---|---|
overrides | object | Mew properties to override in the clone. |
Returns default<Child>
. New node
Container#each()
Iterates through the container’s immediate children,
calling callback
for each child.
Returning false
in the callback will break iteration.
This method only iterates through the container’s immediate children.
If you need to recursively iterate through all the container’s descendant
nodes, use Container#walk
.
Unlike the for {}
-cycle or Array#forEach
this iterator is safe
if you are mutating the array of child nodes during iteration.
PostCSS will adjust the current index to match the mutations.
const root = postcss.parse('a { color: black; z-index: 1 }')
const rule = root.first
for (const decl of rule.nodes) {
decl.cloneBefore({ prop: '-webkit-' + decl.prop })
// Cycle will be infinite, because cloneBefore moves the current node
// to the next index
}
rule.each(decl => {
decl.cloneBefore({ prop: '-webkit-' + decl.prop })
// Will be executed only for color and z-index
})
Argument | Type | Description |
---|---|---|
callback | (node: Child, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Container#error()
Returns a CssSyntaxError
instance containing the original position
of the node in the source, showing line and column numbers and also
a small excerpt to facilitate debugging.
If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).
This method produces very useful error messages.
if (!variables[name]) {
throw decl.error(`Unknown variable ${name}`, { word: name })
// CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
// color: $black
// a
// ^
// background: white
}
Argument | Type | Description |
---|---|---|
message | string | Error description. |
options | NodeErrorOptions |
Returns default
. Error object to throw it.
Container#every()
Returns true
if callback returns true
for all of the container’s children.
const noPrefixes = rule.every(i => i.prop[0] !== '-')
Argument | Type | Description |
---|---|---|
condition | (node: Child, index: number, nodes: Child[]) => boolean | Iterator returns true or false. |
Returns boolean
. Is every child pass condition.
Container#index()
Returns a child
’s index within the Container#nodes
array.
rule.index( rule.nodes[2] ) //=> 2
Argument | Type | Description |
---|---|---|
child | number | Child | Child of the current container. |
Returns number
. Child index.
Container#insertAfter()
Insert new node after old node within the container.
Argument | Type | Description |
---|---|---|
oldNode | number | Child | Child or child’s index. |
newNode | string | ChildProps | Child | Child[] | ChildProps[] | string[] | New node. |
Returns default<Child>
. This node for methods chain.
Container#insertBefore()
Insert new node before old node within the container.
rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
Argument | Type | Description |
---|---|---|
oldNode | number | Child | Child or child’s index. |
newNode | string | ChildProps | Child | Child[] | ChildProps[] | string[] | New node. |
Returns default<Child>
. This node for methods chain.
Container#next()
Returns the next child of the node’s parent.
Returns undefined
if the current node is the last child.
if (comment.text === 'delete next') {
const next = comment.next()
if (next) {
next.remove()
}
}
Argument | Type |
---|
Returns ChildNode
. Next node.
Container#positionBy()
Get the position for a word or an index inside the node.
Argument | Type | Description |
---|---|---|
opts | Pick<WarningOptions, "word" | "index"> | Options. |
Returns Position
. Position.
Container#positionInside()
Convert string index to line/column.
Argument | Type | Description |
---|---|---|
index | number | The symbol number in the node’s string. |
Returns Position
. Symbol position in file.
Container#prepend()
Inserts new nodes to the start of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.prepend(decl1, decl2)
root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
root.append({ selector: 'a' }) // rule
rule.append({ prop: 'color', value: 'black' }) // declaration
rule.append({ text: 'Comment' }) // comment
root.append('a {}')
root.first.append('color: black; z-index: 1')
Argument | Type | Description |
---|---|---|
nodes… | (string | ChildProps | default | default[] | ChildProps[] | string[])[] | New nodes. |
Returns default<Child>
. This node for methods chain.
Container#prev()
Returns the previous child of the node’s parent.
Returns undefined
if the current node is the first child.
const annotation = decl.prev()
if (annotation.type === 'comment') {
readAnnotation(annotation.text)
}
Argument | Type |
---|
Returns ChildNode
. Previous node.
Container#push()
Add child to the end of the node.
rule.push(new Declaration({ prop: 'color', value: 'black' }))
Argument | Type | Description |
---|---|---|
child | Child | New node. |
Returns default<Child>
. This node for methods chain.
Container#rangeBy()
Get the range for a word or start and end index inside the node. The start index is inclusive; the end index is exclusive.
Argument | Type | Description |
---|---|---|
opts | Pick<WarningOptions, "word" | "index" | "endIndex"> | Options. |
Returns Range
. Range.
Container#raw()
Returns a Node#raws
value. If the node is missing
the code style property (because the node was manually built or cloned),
PostCSS will try to autodetect the code style property by looking
at other nodes in the tree.
const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
Argument | 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. |
Returns string
. Code style value.
Container#remove()
Removes the node from its parent and cleans the parent properties from the node and its children.
if (decl.prop.match(/^-webkit-/)) {
decl.remove()
}
Argument | Type |
---|
Returns default<Child>
. Node to make calls chain.
Container#removeAll()
Removes all children from the container and cleans their parent properties.
rule.removeAll()
rule.nodes.length //=> 0
Argument | Type |
---|
Returns default<Child>
. This node for methods chain.
Container#removeChild()
Removes node from the container and cleans the parent properties from the node and its children.
rule.nodes.length //=> 5
rule.removeChild(decl)
rule.nodes.length //=> 4
decl.parent //=> undefined
Argument | Type | Description |
---|---|---|
child | number | Child | Child or child’s index. |
Returns default<Child>
. This node for methods chain.
Container#replaceValues()
Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.
This method is useful if you are using a custom unit or function and need to iterate through all values.
root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
return 15 * parseInt(string) + 'px'
})
Argument | Type | Description |
---|---|---|
pattern | string | RegExp | Replace pattern. |
options | ValueOptions | |
replaced | string | (substring: string, args: any[]) => string |
Argument | Type | Description |
---|---|---|
pattern | string | RegExp | Replace pattern. |
replaced | string | (substring: string, args: any[]) => string |
Returns default<Child>
. This node for methods chain.
Container#replaceWith()
Inserts node(s) before the current node and removes the current node.
AtRule: {
mixin: atrule => {
atrule.replaceWith(mixinRules[atrule.params])
}
}
Argument | Type | Description |
---|---|---|
nodes… | (ChildNode | ChildProps | ChildNode[] | ChildProps[])[] | Mode(s) to replace current one. |
Returns default<Child>
. Current node to methods chain.
Container#root()
Finds the Root instance of the node’s tree.
root.nodes[0].nodes[0].root() === root
Argument | Type |
---|
Returns default
. Root parent.
Container#some()
Returns true
if callback returns true
for (at least) one
of the container’s children.
const hasPrefix = rule.some(i => i.prop[0] === '-')
Argument | Type | Description |
---|---|---|
condition | (node: Child, index: number, nodes: Child[]) => boolean | Iterator returns true or false. |
Returns boolean
. Is some child pass condition.
Container#toJSON()
Fix circular links on JSON.stringify()
.
Argument | Type |
---|
Returns object
. Cleaned object.
Container#toString()
Returns a CSS string representing the node.
new Rule({ selector: 'a' }).toString() //=> "a {}"
Argument | Type | Description |
---|---|---|
stringifier | Stringifier | Syntax | A syntax to use in string generation. |
Returns string
. CSS string of this node.
Container#walk()
Traverses the container’s descendant nodes, calling callback for each node.
Like container.each(), this method is safe to use if you are mutating arrays during iteration.
If you only need to iterate through the container’s immediate children,
use Container#each
.
root.walk(node => {
// Traverses all descendant nodes.
})
Argument | Type | Description |
---|---|---|
callback | (node: ChildNode, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Container#walkAtRules()
Traverses the container’s descendant nodes, calling callback for each at-rule node.
If you pass a filter, iteration will only happen over at-rules that have matching names.
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
root.walkAtRules(rule => {
if (isOld(rule.name)) rule.remove()
})
let first = false
root.walkAtRules('charset', rule => {
if (!first) {
first = true
} else {
rule.remove()
}
})
Argument | Type | Description |
---|---|---|
nameFilter | string | RegExp | |
callback | (atRule: default, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Container#walkComments()
Traverses the container’s descendant nodes, calling callback for each comment node.
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
root.walkComments(comment => {
comment.remove()
})
Argument | Type | Description |
---|---|---|
callback | (comment: default, indexed: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Container#walkDecls()
Traverses the container’s descendant nodes, calling callback for each declaration node.
If you pass a filter, iteration will only happen over declarations with matching properties.
root.walkDecls(decl => {
checkPropertySupport(decl.prop)
})
root.walkDecls('border-radius', decl => {
decl.remove()
})
root.walkDecls(/^background/, decl => {
decl.value = takeFirstColorFromGradient(decl.value)
})
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
Argument | Type | Description |
---|---|---|
propFilter | string | RegExp | |
callback | (decl: default, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Container#walkRules()
Traverses the container’s descendant nodes, calling callback for each rule node.
If you pass a filter, iteration will only happen over rules with matching selectors.
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
const selectors = []
root.walkRules(rule => {
selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
Argument | Type | Description |
---|---|---|
selectorFilter | string | RegExp | |
callback | (rule: default, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Container#warn()
This method is provided as a convenience wrapper for Result#warn
.
Declaration: {
bad: (decl, { result }) => {
decl.warn(result, 'Deprecated property bad')
}
}
Argument | Type | Description |
---|---|---|
result | default | The Result instance that will receive the warning. |
text | string | Warning message. |
opts | WarningOptions | Warning Options. |
Returns default
. Created warning object.
CssSyntaxError
The CSS parser throws this error for broken CSS.
Custom parsers can throw this error for broken custom syntax using
the Node#error
method.
PostCSS will use the input source map to detect the original error location. If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS, PostCSS will show the original position in the Sass file.
If you need the position in the PostCSS input
(e.g., to debug the previous compiler), use error.input.file
.
// Raising error from plugin
throw node.error('Unknown variable', { plugin: 'postcss-vars' })
// Catching and checking syntax error
try {
postcss.parse('a{')
} catch (error) {
if (error.name === 'CssSyntaxError') {
error //=> CssSyntaxError
}
}
CssSyntaxError#column
Source column of the error.
error.column //=> 1
error.input.column //=> 4
PostCSS will use the input source map to detect the original location.
If you need the position in the PostCSS input, use error.input.column
.
Type: number.
CssSyntaxError#endColumn
Source column of the error's end, exclusive. Provided if the error pertains to a range.
error.endColumn //=> 1
error.input.endColumn //=> 4
PostCSS will use the input source map to detect the original location.
If you need the position in the PostCSS input, use error.input.endColumn
.
Type: number.
CssSyntaxError#endLine
Source line of the error's end, exclusive. Provided if the error pertains to a range.
error.endLine //=> 3
error.input.endLine //=> 4
PostCSS will use the input source map to detect the original location.
If you need the position in the PostCSS input, use error.input.endLine
.
Type: number.
CssSyntaxError#file
Absolute path to the broken file.
error.file //=> 'a.sass'
error.input.file //=> 'a.css'
PostCSS will use the input source map to detect the original location.
If you need the position in the PostCSS input, use error.input.file
.
Type: string.
CssSyntaxError#input
Input object with PostCSS internal information about input file. If input has source map from previous tool, PostCSS will use origin (for example, Sass) source. You can use this object to get PostCSS input source.
error.input.file //=> 'a.css'
error.file //=> 'a.sass'
Type: FilePosition.
CssSyntaxError#line
Source line of the error.
error.line //=> 2
error.input.line //=> 4
PostCSS will use the input source map to detect the original location.
If you need the position in the PostCSS input, use error.input.line
.
Type: number.
CssSyntaxError#message
Full error text in the GNU error format with plugin, file, line and column.
error.message //=> 'a.css:1:1: Unclosed block'
Type: string.
CssSyntaxError#name
Always equal to 'CssSyntaxError'
. You should always check error type
by error.name === 'CssSyntaxError'
instead of error instanceof CssSyntaxError
,
because npm could have several PostCSS versions.
if (error.name === 'CssSyntaxError') {
error //=> CssSyntaxError
}
Type: "CssSyntaxError".
CssSyntaxError#plugin
Plugin name, if error came from plugin.
error.plugin //=> 'postcss-vars'
Type: string.
CssSyntaxError#reason
Error message.
error.message //=> 'Unclosed block'
Type: string.
CssSyntaxError#source
Source code of the broken file.
error.source //=> 'a { b {} }'
error.input.source //=> 'a b { }'
Type: string.
CssSyntaxError#stack
Type: string.
CssSyntaxError#showSourceCode()
Returns a few lines of CSS source that caused the error.
If the CSS has an input source map without sourceContent
,
this method will return an empty string.
error.showSourceCode() //=> " 4 | }
// 5 | a {
// > 6 | bad
// | ^
// 7 | }
// 8 | b {"
Argument | 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 . |
Returns string
. Few lines of CSS source that caused the error.
CssSyntaxError#toString()
Returns error position, message and source code of the broken part.
error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block
// > 1 | a {
// | ^"
Argument | Type |
---|
Returns string
. Error position, message and source code.
Declaration
Represents a CSS declaration.
Once (root, { Declaration }) {
let color = new Declaration({ prop: 'color', value: 'black' })
root.append(color)
}
const root = postcss.parse('a { color: black }')
const decl = root.first.first
decl.type //=> 'decl'
decl.toString() //=> ' color: black'
Declaration#important
true
if the declaration has an !important
annotation.
const root = postcss.parse('a { color: black !important; color: red }')
root.first.first.important //=> true
root.first.last.important //=> undefined
Type: boolean.
Declaration#parent
The node’s parent node.
root.nodes[0].parent === root
Type: default<ChildNode>.
Declaration#prop
The declaration's property name.
const root = postcss.parse('a { color: black }')
const decl = root.first.first
decl.prop //=> 'color'
Type: string.
Declaration#raws
Information to generate byte-to-byte equal node string as it was in the origin input.
Every parser saves its own properties, but the default CSS parser uses:
before
: the space symbols before the node. It also stores*
and_
symbols before the declaration (IE hack).after
: the space symbols after the last child of the node to the end of the node.between
: the symbols between the property and value for declarations, selector and{
for rules, or last parameter and{
for at-rules.semicolon
: contains true if the last child has an (optional) semicolon.afterName
: the space between the at-rule name and its parameters.left
: the space symbols between/*
and the comment’s text.right
: the space symbols between the comment’s text and */.important
: the content of the important statement, if it is not just!important
.
PostCSS cleans selectors, declaration values and at-rule parameters from comments and extra spaces, but it stores origin content in raws properties. As such, if you don’t change a declaration’s value, PostCSS will use the raw value with comments.
const root = postcss.parse('a {\n color:black\n}')
root.first.first.raws //=> { before: '\n ', between: ':' }
Type: DeclarationRaws.
Declaration#source
The input source of the node.
The property is used in source map generation.
If you create a node manually (e.g., with postcss.decl()
),
that node will not have a source
property and will be absent
from the source map. For this reason, the plugin developer should
consider cloning nodes to create new ones (in which case the new node’s
source will reference the original, cloned node) or setting
the source
property manually.
decl.source.input.from //=> '/home/ai/a.sass'
decl.source.start //=> { line: 10, column: 2 }
decl.source.end //=> { line: 10, column: 12 }
// Bad
const prefixed = postcss.decl({
prop: '-moz-' + decl.prop,
value: decl.value
})
// Good
const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
if (atrule.name === 'add-link') {
const rule = postcss.rule({ selector: 'a', source: atrule.source })
atrule.parent.insertBefore(atrule, rule)
}
Type: Source.
Declaration#type
tring representing the node’s type. Possible values are root
, atrule
,
rule
, decl
, or comment
.
new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
Type: "decl".
Declaration#value
The declaration’s value.
This value will be cleaned of comments. If the source value contained
comments, those comments will be available in the raws
property.
If you have not changed the value, the result of decl.toString()
will include the original raws value (comments and all).
const root = postcss.parse('a { color: black }')
const decl = root.first.first
decl.value //=> 'black'
Type: string.
Declaration#variable
true
if declaration is declaration of CSS Custom Property
or Sass variable.
const root = postcss.parse(':root { --one: 1 }')
let one = root.first.first
one.variable //=> true
const root = postcss.parse('$one: 1')
let one = root.first
one.variable //=> true
Type: boolean.
Declaration#after()
Insert new node after current node to current node’s parent.
Just alias for node.parent.insertAfter(node, add)
.
decl.after('color: black')
Argument | Type | Description |
---|---|---|
newNode | string | ChildProps | default | default[] | New node. |
Returns default
. This node for methods chain.
Declaration#assign()
Assigns properties to the current node.
decl.assign({ prop: 'word-wrap', value: 'break-word' })
Argument | Type | Description |
---|---|---|
overrides | object | DeclarationProps | New properties to override the node. |
Returns default
.
Declaration#before()
Insert new node before current node to current node’s parent.
Just alias for node.parent.insertBefore(node, add)
.
decl.before('content: ""')
Argument | Type | Description |
---|---|---|
newNode | string | ChildProps | default | default[] | New node. |
Returns default
. This node for methods chain.
Declaration#cleanRaws()
Clear the code style properties for the node and its children.
node.raws.before //=> ' '
node.cleanRaws()
node.raws.before //=> undefined
Argument | Type | Description |
---|---|---|
keepBetween | boolean | Keep the raws.between symbols. |
Declaration#clone()
Returns an exact clone of the node.
The resulting cloned node and its (cloned) children will retain code style properties.
decl.raws.before //=> "\n "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before //=> "\n "
cloned.toString() //=> -moz-transform: scale(0)
Argument | Type | Description |
---|---|---|
overrides | Partial<DeclarationProps> | New properties to override in the clone. |
Returns default
.
Declaration#cloneAfter()
Shortcut to clone the node and insert the resulting cloned node after the current node.
Argument | Type | Description |
---|---|---|
overrides | Partial<DeclarationProps> | New properties to override in the clone. |
Returns default
.
Declaration#cloneBefore()
Shortcut to clone the node and insert the resulting cloned node before the current node.
decl.cloneBefore({ prop: '-moz-' + decl.prop })
Argument | Type | Description |
---|---|---|
overrides | Partial<DeclarationProps> | Mew properties to override in the clone. |
Returns default
.
Declaration#error()
Returns a CssSyntaxError
instance containing the original position
of the node in the source, showing line and column numbers and also
a small excerpt to facilitate debugging.
If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).
This method produces very useful error messages.
if (!variables[name]) {
throw decl.error(`Unknown variable ${name}`, { word: name })
// CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
// color: $black
// a
// ^
// background: white
}
Argument | Type | Description |
---|---|---|
message | string | Error description. |
options | NodeErrorOptions |
Returns default
. Error object to throw it.
Declaration#next()
Returns the next child of the node’s parent.
Returns undefined
if the current node is the last child.
if (comment.text === 'delete next') {
const next = comment.next()
if (next) {
next.remove()
}
}
Argument | Type |
---|
Returns ChildNode
. Next node.
Declaration#positionBy()
Get the position for a word or an index inside the node.
Argument | Type | Description |
---|---|---|
opts | Pick<WarningOptions, "word" | "index"> | Options. |
Returns Position
. Position.
Declaration#positionInside()
Convert string index to line/column.
Argument | Type | Description |
---|---|---|
index | number | The symbol number in the node’s string. |
Returns Position
. Symbol position in file.
Declaration#prev()
Returns the previous child of the node’s parent.
Returns undefined
if the current node is the first child.
const annotation = decl.prev()
if (annotation.type === 'comment') {
readAnnotation(annotation.text)
}
Argument | Type |
---|
Returns ChildNode
. Previous node.
Declaration#rangeBy()
Get the range for a word or start and end index inside the node. The start index is inclusive; the end index is exclusive.
Argument | Type | Description |
---|---|---|
opts | Pick<WarningOptions, "word" | "index" | "endIndex"> | Options. |
Returns Range
. Range.
Declaration#raw()
Returns a Node#raws
value. If the node is missing
the code style property (because the node was manually built or cloned),
PostCSS will try to autodetect the code style property by looking
at other nodes in the tree.
const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
Argument | 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. |
Returns string
. Code style value.
Declaration#remove()
Removes the node from its parent and cleans the parent properties from the node and its children.
if (decl.prop.match(/^-webkit-/)) {
decl.remove()
}
Argument | Type |
---|
Returns default
. Node to make calls chain.
Declaration#replaceWith()
Inserts node(s) before the current node and removes the current node.
AtRule: {
mixin: atrule => {
atrule.replaceWith(mixinRules[atrule.params])
}
}
Argument | Type | Description |
---|---|---|
nodes… | (ChildNode | ChildProps | ChildNode[] | ChildProps[])[] | Mode(s) to replace current one. |
Returns default
. Current node to methods chain.
Declaration#root()
Finds the Root instance of the node’s tree.
root.nodes[0].nodes[0].root() === root
Argument | Type |
---|
Returns default
. Root parent.
Declaration#toJSON()
Fix circular links on JSON.stringify()
.
Argument | Type |
---|
Returns object
. Cleaned object.
Declaration#toString()
Returns a CSS string representing the node.
new Rule({ selector: 'a' }).toString() //=> "a {}"
Argument | Type | Description |
---|---|---|
stringifier | Stringifier | Syntax | A syntax to use in string generation. |
Returns string
. CSS string of this node.
Declaration#warn()
This method is provided as a convenience wrapper for Result#warn
.
Declaration: {
bad: (decl, { result }) => {
decl.warn(result, 'Deprecated property bad')
}
}
Argument | Type | Description |
---|---|---|
result | default | The Result instance that will receive the warning. |
text | string | Warning message. |
opts | WarningOptions | Warning Options. |
Returns default
. Created warning object.
Document
Represents a file and contains all its parsed nodes.
Experimental: some aspects of this node could change within minor or patch version releases.
const document = htmlParser(
'<html><style>a{color:black}</style><style>b{z-index:2}</style>'
)
document.type //=> 'document'
document.nodes.length //=> 2
Document#nodes
An array containing the container’s children.
const root = postcss.parse('a { color: black }')
root.nodes.length //=> 1
root.nodes[0].selector //=> 'a'
root.nodes[0].nodes[0].prop //=> 'color'
Type: default[].
Document#parent
The node’s parent node.
root.nodes[0].parent === root
Type: undefined.
Document#raws
Information to generate byte-to-byte equal node string as it was in the origin input.
Every parser saves its own properties, but the default CSS parser uses:
before
: the space symbols before the node. It also stores*
and_
symbols before the declaration (IE hack).after
: the space symbols after the last child of the node to the end of the node.between
: the symbols between the property and value for declarations, selector and{
for rules, or last parameter and{
for at-rules.semicolon
: contains true if the last child has an (optional) semicolon.afterName
: the space between the at-rule name and its parameters.left
: the space symbols between/*
and the comment’s text.right
: the space symbols between the comment’s text and */.important
: the content of the important statement, if it is not just!important
.
PostCSS cleans selectors, declaration values and at-rule parameters from comments and extra spaces, but it stores origin content in raws properties. As such, if you don’t change a declaration’s value, PostCSS will use the raw value with comments.
const root = postcss.parse('a {\n color:black\n}')
root.first.first.raws //=> { before: '\n ', between: ':' }
Type: any.
Document#source
The input source of the node.
The property is used in source map generation.
If you create a node manually (e.g., with postcss.decl()
),
that node will not have a source
property and will be absent
from the source map. For this reason, the plugin developer should
consider cloning nodes to create new ones (in which case the new node’s
source will reference the original, cloned node) or setting
the source
property manually.
decl.source.input.from //=> '/home/ai/a.sass'
decl.source.start //=> { line: 10, column: 2 }
decl.source.end //=> { line: 10, column: 12 }
// Bad
const prefixed = postcss.decl({
prop: '-moz-' + decl.prop,
value: decl.value
})
// Good
const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
if (atrule.name === 'add-link') {
const rule = postcss.rule({ selector: 'a', source: atrule.source })
atrule.parent.insertBefore(atrule, rule)
}
Type: Source.
Document#type
tring representing the node’s type. Possible values are root
, atrule
,
rule
, decl
, or comment
.
new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
Type: "document".
Document#first
The container’s first child.
rule.first === rules.nodes[0]
Document#last
The container’s last child.
rule.last === rule.nodes[rule.nodes.length - 1]
Document#after()
Insert new node after current node to current node’s parent.
Just alias for node.parent.insertAfter(node, add)
.
decl.after('color: black')
Argument | Type | Description |
---|---|---|
newNode | string | ChildProps | default | default[] | New node. |
Returns default
. This node for methods chain.
Document#append()
Inserts new nodes to the end of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.append(decl1, decl2)
root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
root.append({ selector: 'a' }) // rule
rule.append({ prop: 'color', value: 'black' }) // declaration
rule.append({ text: 'Comment' }) // comment
root.append('a {}')
root.first.append('color: black; z-index: 1')
Argument | Type | Description |
---|---|---|
nodes… | (string | ChildProps | default | default[] | ChildProps[] | string[])[] | New nodes. |
Returns default
. This node for methods chain.
Document#assign()
Assigns properties to the current node.
decl.assign({ prop: 'word-wrap', value: 'break-word' })
Argument | Type | Description |
---|---|---|
overrides | object | New properties to override the node. |
Returns default
. Current node to methods chain.
Document#before()
Insert new node before current node to current node’s parent.
Just alias for node.parent.insertBefore(node, add)
.
decl.before('content: ""')
Argument | Type | Description |
---|---|---|
newNode | string | ChildProps | default | default[] | New node. |
Returns default
. This node for methods chain.
Document#cleanRaws()
Clear the code style properties for the node and its children.
node.raws.before //=> ' '
node.cleanRaws()
node.raws.before //=> undefined
Argument | Type | Description |
---|---|---|
keepBetween | boolean | Keep the raws.between symbols. |
Document#clone()
Returns an exact clone of the node.
The resulting cloned node and its (cloned) children will retain code style properties.
decl.raws.before //=> "\n "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before //=> "\n "
cloned.toString() //=> -moz-transform: scale(0)
Argument | Type | Description |
---|---|---|
overrides | object | New properties to override in the clone. |
Returns default
. Clone of the node.
Document#cloneAfter()
Shortcut to clone the node and insert the resulting cloned node after the current node.
Argument | Type | Description |
---|---|---|
overrides | object | New properties to override in the clone. |
Returns default
. New node.
Document#cloneBefore()
Shortcut to clone the node and insert the resulting cloned node before the current node.
decl.cloneBefore({ prop: '-moz-' + decl.prop })
Argument | Type | Description |
---|---|---|
overrides | object | Mew properties to override in the clone. |
Returns default
. New node
Document#each()
Iterates through the container’s immediate children,
calling callback
for each child.
Returning false
in the callback will break iteration.
This method only iterates through the container’s immediate children.
If you need to recursively iterate through all the container’s descendant
nodes, use Container#walk
.
Unlike the for {}
-cycle or Array#forEach
this iterator is safe
if you are mutating the array of child nodes during iteration.
PostCSS will adjust the current index to match the mutations.
const root = postcss.parse('a { color: black; z-index: 1 }')
const rule = root.first
for (const decl of rule.nodes) {
decl.cloneBefore({ prop: '-webkit-' + decl.prop })
// Cycle will be infinite, because cloneBefore moves the current node
// to the next index
}
rule.each(decl => {
decl.cloneBefore({ prop: '-webkit-' + decl.prop })
// Will be executed only for color and z-index
})
Argument | Type | Description |
---|---|---|
callback | (node: default, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Document#error()
Returns a CssSyntaxError
instance containing the original position
of the node in the source, showing line and column numbers and also
a small excerpt to facilitate debugging.
If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).
This method produces very useful error messages.
if (!variables[name]) {
throw decl.error(`Unknown variable ${name}`, { word: name })
// CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
// color: $black
// a
// ^
// background: white
}
Argument | Type | Description |
---|---|---|
message | string | Error description. |
options | NodeErrorOptions |
Returns default
. Error object to throw it.
Document#every()
Returns true
if callback returns true
for all of the container’s children.
const noPrefixes = rule.every(i => i.prop[0] !== '-')
Argument | Type | Description |
---|---|---|
condition | (node: default, index: number, nodes: default[]) => boolean | Iterator returns true or false. |
Returns boolean
. Is every child pass condition.
Document#index()
Returns a child
’s index within the Container#nodes
array.
rule.index( rule.nodes[2] ) //=> 2
Argument | Type | Description |
---|---|---|
child | number | default | Child of the current container. |
Returns number
. Child index.
Document#insertAfter()
Insert new node after old node within the container.
Argument | Type | Description |
---|---|---|
oldNode | number | default | Child or child’s index. |
newNode | string | ChildProps | ChildProps[] | string[] | default | default[] | New node. |
Returns default
. This node for methods chain.
Document#insertBefore()
Insert new node before old node within the container.
rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
Argument | Type | Description |
---|---|---|
oldNode | number | default | Child or child’s index. |
newNode | string | ChildProps | ChildProps[] | string[] | default | default[] | New node. |
Returns default
. This node for methods chain.
Document#next()
Returns the next child of the node’s parent.
Returns undefined
if the current node is the last child.
if (comment.text === 'delete next') {
const next = comment.next()
if (next) {
next.remove()
}
}
Argument | Type |
---|
Returns ChildNode
. Next node.
Document#positionBy()
Get the position for a word or an index inside the node.
Argument | Type | Description |
---|---|---|
opts | Pick<WarningOptions, "word" | "index"> | Options. |
Returns Position
. Position.
Document#positionInside()
Convert string index to line/column.
Argument | Type | Description |
---|---|---|
index | number | The symbol number in the node’s string. |
Returns Position
. Symbol position in file.
Document#prepend()
Inserts new nodes to the start of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.prepend(decl1, decl2)
root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
root.append({ selector: 'a' }) // rule
rule.append({ prop: 'color', value: 'black' }) // declaration
rule.append({ text: 'Comment' }) // comment
root.append('a {}')
root.first.append('color: black; z-index: 1')
Argument | Type | Description |
---|---|---|
nodes… | (string | ChildProps | default | default[] | ChildProps[] | string[])[] | New nodes. |
Returns default
. This node for methods chain.
Document#prev()
Returns the previous child of the node’s parent.
Returns undefined
if the current node is the first child.
const annotation = decl.prev()
if (annotation.type === 'comment') {
readAnnotation(annotation.text)
}
Argument | Type |
---|
Returns ChildNode
. Previous node.
Document#push()
Add child to the end of the node.
rule.push(new Declaration({ prop: 'color', value: 'black' }))
Argument | Type | Description |
---|---|---|
child | default | New node. |
Returns default
. This node for methods chain.
Document#rangeBy()
Get the range for a word or start and end index inside the node. The start index is inclusive; the end index is exclusive.
Argument | Type | Description |
---|---|---|
opts | Pick<WarningOptions, "word" | "index" | "endIndex"> | Options. |
Returns Range
. Range.
Document#raw()
Returns a Node#raws
value. If the node is missing
the code style property (because the node was manually built or cloned),
PostCSS will try to autodetect the code style property by looking
at other nodes in the tree.
const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
Argument | 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. |
Returns string
. Code style value.
Document#remove()
Removes the node from its parent and cleans the parent properties from the node and its children.
if (decl.prop.match(/^-webkit-/)) {
decl.remove()
}
Argument | Type |
---|
Returns default
. Node to make calls chain.
Document#removeAll()
Removes all children from the container and cleans their parent properties.
rule.removeAll()
rule.nodes.length //=> 0
Argument | Type |
---|
Returns default
. This node for methods chain.
Document#removeChild()
Removes node from the container and cleans the parent properties from the node and its children.
rule.nodes.length //=> 5
rule.removeChild(decl)
rule.nodes.length //=> 4
decl.parent //=> undefined
Argument | Type | Description |
---|---|---|
child | number | default | Child or child’s index. |
Returns default
. This node for methods chain.
Document#replaceValues()
Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.
This method is useful if you are using a custom unit or function and need to iterate through all values.
root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
return 15 * parseInt(string) + 'px'
})
Argument | Type | Description |
---|---|---|
pattern | string | RegExp | Replace pattern. |
options | ValueOptions | |
replaced | string | (substring: string, args: any[]) => string |
Argument | Type | Description |
---|---|---|
pattern | string | RegExp | Replace pattern. |
replaced | string | (substring: string, args: any[]) => string |
Returns default
. This node for methods chain.
Document#replaceWith()
Inserts node(s) before the current node and removes the current node.
AtRule: {
mixin: atrule => {
atrule.replaceWith(mixinRules[atrule.params])
}
}
Argument | Type | Description |
---|---|---|
nodes… | (ChildNode | ChildProps | ChildNode[] | ChildProps[])[] | Mode(s) to replace current one. |
Returns default
. Current node to methods chain.
Document#root()
Finds the Root instance of the node’s tree.
root.nodes[0].nodes[0].root() === root
Argument | Type |
---|
Returns default
. Root parent.
Document#some()
Returns true
if callback returns true
for (at least) one
of the container’s children.
const hasPrefix = rule.some(i => i.prop[0] === '-')
Argument | Type | Description |
---|---|---|
condition | (node: default, index: number, nodes: default[]) => boolean | Iterator returns true or false. |
Returns boolean
. Is some child pass condition.
Document#toJSON()
Fix circular links on JSON.stringify()
.
Argument | Type |
---|
Returns object
. Cleaned object.
Document#toResult()
Returns a Result
instance representing the document’s CSS roots.
const root1 = postcss.parse(css1, { from: 'a.css' })
const root2 = postcss.parse(css2, { from: 'b.css' })
const document = postcss.document()
document.append(root1)
document.append(root2)
const result = document.toResult({ to: 'all.css', map: true })
Argument | Type |
---|---|
options | ProcessOptions |
Returns default
. Result with current document’s CSS.
Document#toString()
Returns a CSS string representing the node.
new Rule({ selector: 'a' }).toString() //=> "a {}"
Argument | Type | Description |
---|---|---|
stringifier | Stringifier | Syntax | A syntax to use in string generation. |
Returns string
. CSS string of this node.
Document#walk()
Traverses the container’s descendant nodes, calling callback for each node.
Like container.each(), this method is safe to use if you are mutating arrays during iteration.
If you only need to iterate through the container’s immediate children,
use Container#each
.
root.walk(node => {
// Traverses all descendant nodes.
})
Argument | Type | Description |
---|---|---|
callback | (node: ChildNode, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Document#walkAtRules()
Traverses the container’s descendant nodes, calling callback for each at-rule node.
If you pass a filter, iteration will only happen over at-rules that have matching names.
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
root.walkAtRules(rule => {
if (isOld(rule.name)) rule.remove()
})
let first = false
root.walkAtRules('charset', rule => {
if (!first) {
first = true
} else {
rule.remove()
}
})
Argument | Type | Description |
---|---|---|
nameFilter | string | RegExp | |
callback | (atRule: default, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Document#walkComments()
Traverses the container’s descendant nodes, calling callback for each comment node.
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
root.walkComments(comment => {
comment.remove()
})
Argument | Type | Description |
---|---|---|
callback | (comment: default, indexed: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Document#walkDecls()
Traverses the container’s descendant nodes, calling callback for each declaration node.
If you pass a filter, iteration will only happen over declarations with matching properties.
root.walkDecls(decl => {
checkPropertySupport(decl.prop)
})
root.walkDecls('border-radius', decl => {
decl.remove()
})
root.walkDecls(/^background/, decl => {
decl.value = takeFirstColorFromGradient(decl.value)
})
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
Argument | Type | Description |
---|---|---|
propFilter | string | RegExp | |
callback | (decl: default, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Document#walkRules()
Traverses the container’s descendant nodes, calling callback for each rule node.
If you pass a filter, iteration will only happen over rules with matching selectors.
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
const selectors = []
root.walkRules(rule => {
selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
Argument | Type | Description |
---|---|---|
selectorFilter | string | RegExp | |
callback | (rule: default, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Document#warn()
This method is provided as a convenience wrapper for Result#warn
.
Declaration: {
bad: (decl, { result }) => {
decl.warn(result, 'Deprecated property bad')
}
}
Argument | Type | Description |
---|---|---|
result | default | The Result instance that will receive the warning. |
text | string | Warning message. |
opts | WarningOptions | Warning Options. |
Returns default
. Created warning object.
Input
Represents the source CSS.
const root = postcss.parse(css, { from: file })
const input = root.source.input
Input#css
Input CSS source.
const input = postcss.parse('a{}', { from: file }).input
input.css //=> "a{}"
Type: string.
Input#file
The absolute path to the CSS source file defined
with the from
option.
const root = postcss.parse(css, { from: 'a.css' })
root.source.input.file //=> '/home/ai/a.css'
Type: string.
Input#hasBOM
The flag to indicate whether or not the source code has Unicode BOM.
Type: boolean.
Input#id
The unique ID of the CSS source. It will be created if from
option
is not provided (because PostCSS does not know the file path).
const root = postcss.parse(css)
root.source.input.file //=> undefined
root.source.input.id //=> "<input css 8LZeVF>"
Type: string.
Input#map
The input source map passed from a compilation step before PostCSS (for example, from Sass compiler).
root.source.input.map.consumer().sources //=> ['a.sass']
Type: default.
Input#from
The CSS source identifier. Contains Input#file
if the user
set the from
option, or Input#id
if they did not.
const root = postcss.parse(css, { from: 'a.css' })
root.source.input.from //=> "/home/ai/a.css"
const root = postcss.parse(css)
root.source.input.from //=> "<input css 1>"
Input#fromOffset()
Converts source offset to line and column.
Argument | Type | Description |
---|---|---|
offset | number | Source offset. |
Returns { col: number, line: number }
.
Input#origin()
Reads the input source map and returns a symbol position in the input source (e.g., in a Sass file that was compiled to CSS before being passed to PostCSS). Optionally takes an end position, exclusive.
root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }
root.source.input.origin(1, 1, 1, 4)
//=> { file: 'a.css', line: 3, column: 1, endLine: 3, endColumn: 4 }
Argument | Type | Description |
---|---|---|
line | number | Line for inclusive start position in input CSS. |
column | number | Column for inclusive start position in input CSS. |
endLine | number | Line for exclusive end position in input CSS. |
endColumn | number | Column for exclusive end position in input CSS. |
Returns false | FilePosition
. Position in input source.
LazyResult
A Promise proxy for the result of PostCSS transformations.
A LazyResult
instance is returned by Processor#process
.
const lazy = postcss([autoprefixer]).process(css)
LazyResult#catch
Processes input CSS through synchronous and asynchronous plugins and calls onRejected for each error thrown in any plugin.
It implements standard Promise API.
postcss([autoprefixer]).process(css).then(result => {
console.log(result.css)
}).catch(error => {
console.error(error)
})
Type: (onrejected: (reason: any) => TResult | PromiseLike<TResult>) => Promise<default | TResult>.
LazyResult#finally
Processes input CSS through synchronous and asynchronous plugins and calls onFinally on any error or when all plugins will finish work.
It implements standard Promise API.
postcss([autoprefixer]).process(css).finally(() => {
console.log('processing ended')
})
Type: (onfinally: () => void) => Promise<default>.
LazyResult#then
Processes input CSS through synchronous and asynchronous plugins
and calls onFulfilled
with a Result instance. If a plugin throws
an error, the onRejected
callback will be executed.
It implements standard Promise API.
postcss([autoprefixer]).process(css, { from: cssPath }).then(result => {
console.log(result.css)
})
Type: (onfulfilled: (value: default) => TResult1 | PromiseLike<TResult1>, onrejected: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<TResult1 | TResult2>.
LazyResult#[toStringTag]
Returns the default string description of an object. Required to implement the Promise interface.
LazyResult#content
An alias for the css
property. Use it with syntaxes
that generate non-CSS output.
This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use LazyResult#then
.
LazyResult#css
Processes input CSS through synchronous plugins, converts Root
to a CSS string and returns Result#css
.
This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use LazyResult#then
.
LazyResult#map
Processes input CSS through synchronous plugins
and returns Result#map
.
This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use LazyResult#then
.
LazyResult#messages
Processes input CSS through synchronous plugins
and returns Result#messages
.
This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use LazyResult#then
.
LazyResult#opts
Options from the Processor#process
call.
LazyResult#processor
Returns a Processor
instance, which will be used
for CSS transformations.
LazyResult#root
Processes input CSS through synchronous plugins
and returns Result#root
.
This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use LazyResult#then
.
LazyResult#async()
Run plugin in async way and return Result
.
Argument | Type |
---|
Returns Promise<default>
. Result with output content.
LazyResult#sync()
Run plugin in sync way and return Result
.
Argument | Type |
---|
Returns default
. Result with output content.
LazyResult#toString()
Alias for the LazyResult#css
property.
lazy + '' === lazy.css
Argument | Type |
---|
Returns string
. Output CSS.
LazyResult#warnings()
Processes input CSS through synchronous plugins
and calls Result#warnings
.
Argument | Type |
---|
Returns default[]
. Warnings from plugins.
NoWorkResult
A Promise proxy for the result of PostCSS transformations.
This lazy result instance doesn't parse css unless NoWorkResult#root
or Result#root
are accessed. See the example below for details.
A NoWork
instance is returned by Processor#process
ONLY when no plugins defined.
const noWorkResult = postcss().process(css) // No plugins are defined.
// CSS is not parsed
let root = noWorkResult.root // now css is parsed because we accessed the root
NoWorkResult#catch
Type: (onrejected: (reason: any) => TResult | PromiseLike<TResult>) => Promise<default | TResult>.
NoWorkResult#finally
Type: (onfinally: () => void) => Promise<default>.
NoWorkResult#then
Type: (onfulfilled: (value: default) => TResult1 | PromiseLike<TResult1>, onrejected: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<TResult1 | TResult2>.
NoWorkResult#[toStringTag]
NoWorkResult#content
NoWorkResult#css
NoWorkResult#map
NoWorkResult#messages
NoWorkResult#opts
NoWorkResult#processor
NoWorkResult#root
NoWorkResult#async()
Argument | Type |
---|
Returns Promise<default>
.
NoWorkResult#sync()
Argument | Type |
---|
Returns default
.
NoWorkResult#toString()
Argument | Type |
---|
Returns string
.
NoWorkResult#warnings()
Argument | Type |
---|
Returns default[]
.
Node
All node classes inherit the following common methods.
You should not extend this classes to create AST for selector or value parser.
Node#parent
The node’s parent node.
root.nodes[0].parent === root
Type: default<ChildNode> | default.
Node#raws
Information to generate byte-to-byte equal node string as it was in the origin input.
Every parser saves its own properties, but the default CSS parser uses:
before
: the space symbols before the node. It also stores*
and_
symbols before the declaration (IE hack).after
: the space symbols after the last child of the node to the end of the node.between
: the symbols between the property and value for declarations, selector and{
for rules, or last parameter and{
for at-rules.semicolon
: contains true if the last child has an (optional) semicolon.afterName
: the space between the at-rule name and its parameters.left
: the space symbols between/*
and the comment’s text.right
: the space symbols between the comment’s text and */.important
: the content of the important statement, if it is not just!important
.
PostCSS cleans selectors, declaration values and at-rule parameters from comments and extra spaces, but it stores origin content in raws properties. As such, if you don’t change a declaration’s value, PostCSS will use the raw value with comments.
const root = postcss.parse('a {\n color:black\n}')
root.first.first.raws //=> { before: '\n ', between: ':' }
Type: any.
Node#source
The input source of the node.
The property is used in source map generation.
If you create a node manually (e.g., with postcss.decl()
),
that node will not have a source
property and will be absent
from the source map. For this reason, the plugin developer should
consider cloning nodes to create new ones (in which case the new node’s
source will reference the original, cloned node) or setting
the source
property manually.
decl.source.input.from //=> '/home/ai/a.sass'
decl.source.start //=> { line: 10, column: 2 }
decl.source.end //=> { line: 10, column: 12 }
// Bad
const prefixed = postcss.decl({
prop: '-moz-' + decl.prop,
value: decl.value
})
// Good
const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
if (atrule.name === 'add-link') {
const rule = postcss.rule({ selector: 'a', source: atrule.source })
atrule.parent.insertBefore(atrule, rule)
}
Type: Source.
Node#type
tring representing the node’s type. Possible values are root
, atrule
,
rule
, decl
, or comment
.
new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
Type: string.
Node#after()
Insert new node after current node to current node’s parent.
Just alias for node.parent.insertAfter(node, add)
.
decl.after('color: black')
Argument | Type | Description |
---|---|---|
newNode | string | ChildProps | default | default[] | New node. |
Returns default
. This node for methods chain.
Node#assign()
Assigns properties to the current node.
decl.assign({ prop: 'word-wrap', value: 'break-word' })
Argument | Type | Description |
---|---|---|
overrides | object | New properties to override the node. |
Returns default
. Current node to methods chain.
Node#before()
Insert new node before current node to current node’s parent.
Just alias for node.parent.insertBefore(node, add)
.
decl.before('content: ""')
Argument | Type | Description |
---|---|---|
newNode | string | ChildProps | default | default[] | New node. |
Returns default
. This node for methods chain.
Node#cleanRaws()
Clear the code style properties for the node and its children.
node.raws.before //=> ' '
node.cleanRaws()
node.raws.before //=> undefined
Argument | Type | Description |
---|---|---|
keepBetween | boolean | Keep the raws.between symbols. |
Node#clone()
Returns an exact clone of the node.
The resulting cloned node and its (cloned) children will retain code style properties.
decl.raws.before //=> "\n "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before //=> "\n "
cloned.toString() //=> -moz-transform: scale(0)
Argument | Type | Description |
---|---|---|
overrides | object | New properties to override in the clone. |
Returns default
. Clone of the node.
Node#cloneAfter()
Shortcut to clone the node and insert the resulting cloned node after the current node.
Argument | Type | Description |
---|---|---|
overrides | object | New properties to override in the clone. |
Returns default
. New node.
Node#cloneBefore()
Shortcut to clone the node and insert the resulting cloned node before the current node.
decl.cloneBefore({ prop: '-moz-' + decl.prop })
Argument | Type | Description |
---|---|---|
overrides | object | Mew properties to override in the clone. |
Returns default
. New node
Node#error()
Returns a CssSyntaxError
instance containing the original position
of the node in the source, showing line and column numbers and also
a small excerpt to facilitate debugging.
If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).
This method produces very useful error messages.
if (!variables[name]) {
throw decl.error(`Unknown variable ${name}`, { word: name })
// CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
// color: $black
// a
// ^
// background: white
}
Argument | Type | Description |
---|---|---|
message | string | Error description. |
options | NodeErrorOptions |
Returns default
. Error object to throw it.
Node#next()
Returns the next child of the node’s parent.
Returns undefined
if the current node is the last child.
if (comment.text === 'delete next') {
const next = comment.next()
if (next) {
next.remove()
}
}
Argument | Type |
---|
Returns ChildNode
. Next node.
Node#positionBy()
Get the position for a word or an index inside the node.
Argument | Type | Description |
---|---|---|
opts | Pick<WarningOptions, "word" | "index"> | Options. |
Returns Position
. Position.
Node#positionInside()
Convert string index to line/column.
Argument | Type | Description |
---|---|---|
index | number | The symbol number in the node’s string. |
Returns Position
. Symbol position in file.
Node#prev()
Returns the previous child of the node’s parent.
Returns undefined
if the current node is the first child.
const annotation = decl.prev()
if (annotation.type === 'comment') {
readAnnotation(annotation.text)
}
Argument | Type |
---|
Returns ChildNode
. Previous node.
Node#rangeBy()
Get the range for a word or start and end index inside the node. The start index is inclusive; the end index is exclusive.
Argument | Type | Description |
---|---|---|
opts | Pick<WarningOptions, "word" | "index" | "endIndex"> | Options. |
Returns Range
. Range.
Node#raw()
Returns a Node#raws
value. If the node is missing
the code style property (because the node was manually built or cloned),
PostCSS will try to autodetect the code style property by looking
at other nodes in the tree.
const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
Argument | 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. |
Returns string
. Code style value.
Node#remove()
Removes the node from its parent and cleans the parent properties from the node and its children.
if (decl.prop.match(/^-webkit-/)) {
decl.remove()
}
Argument | Type |
---|
Returns default
. Node to make calls chain.
Node#replaceWith()
Inserts node(s) before the current node and removes the current node.
AtRule: {
mixin: atrule => {
atrule.replaceWith(mixinRules[atrule.params])
}
}
Argument | Type | Description |
---|---|---|
nodes… | (ChildNode | ChildProps | ChildNode[] | ChildProps[])[] | Mode(s) to replace current one. |
Returns default
. Current node to methods chain.
Node#root()
Finds the Root instance of the node’s tree.
root.nodes[0].nodes[0].root() === root
Argument | Type |
---|
Returns default
. Root parent.
Node#toJSON()
Fix circular links on JSON.stringify()
.
Argument | Type |
---|
Returns object
. Cleaned object.
Node#toString()
Returns a CSS string representing the node.
new Rule({ selector: 'a' }).toString() //=> "a {}"
Argument | Type | Description |
---|---|---|
stringifier | Stringifier | Syntax | A syntax to use in string generation. |
Returns string
. CSS string of this node.
Node#warn()
This method is provided as a convenience wrapper for Result#warn
.
Declaration: {
bad: (decl, { result }) => {
decl.warn(result, 'Deprecated property bad')
}
}
Argument | Type | Description |
---|---|---|
result | default | The Result instance that will receive the warning. |
text | string | Warning message. |
opts | WarningOptions | Warning Options. |
Returns default
. Created warning object.
PreviousMap
Source map information from input CSS. For example, source map after Sass compiler.
This class will automatically find source map in input CSS or in file system
near input file (according from
option).
const root = parse(css, { from: 'a.sass.css' })
root.input.map //=> PreviousMap
PreviousMap#annotation
sourceMappingURL
content.
Type: string.
PreviousMap#file
The CSS source identifier. Contains Input#file
if the user
set the from
option, or Input#id
if they did not.
Type: string.
PreviousMap#inline
Was source map inlined by data-uri to input CSS.
Type: boolean.
PreviousMap#mapFile
Path to source map file.
Type: string.
PreviousMap#root
The directory with source map file, if source map is in separated file.
Type: string.
PreviousMap#text
Source map file content.
Type: string.
PreviousMap#consumer()
Create a instance of SourceMapGenerator
class
from the source-map
library to work with source map information.
It is lazy method, so it will create object only on first call and then it will use cache.
Argument | Type |
---|
Returns SourceMapConsumer
. Object with source map information.
PreviousMap#withContent()
Does source map contains sourcesContent
with input source text.
Argument | Type |
---|
Returns boolean
. Is sourcesContent
present.
Processor
Contains plugins to process CSS. Create one Processor
instance,
initialize its plugins, and then use that instance on numerous CSS files.
const processor = postcss([autoprefixer, postcssNested])
processor.process(css1).then(result => console.log(result.css))
processor.process(css2).then(result => console.log(result.css))
Processor#plugins
Plugins added to this processor.
const processor = postcss([autoprefixer, postcssNested])
processor.plugins.length //=> 2
Type: (Plugin | Transformer | TransformCallback)[].
Processor#version
Current PostCSS version.
if (result.processor.version.split('.')[0] !== '6') {
throw new Error('This plugin works only with PostCSS 6')
}
Type: string.
Processor#process()
Parses source CSS and returns a LazyResult
Promise proxy.
Because some plugins can be asynchronous it doesn’t make
any transformations. Transformations will be applied
in the LazyResult
methods.
processor.process(css, { from: 'a.css', to: 'a.out.css' })
.then(result => {
console.log(result.css)
})
Argument | Type | Description |
---|---|---|
css | string | default | default | default | { toString: () => string } | String with input CSS or any object with a toString() method,
like a Buffer. Optionally, senda Result instance
and the processor will take the Root from it. |
options | ProcessOptions |
Returns default | default
. Promise proxy.
Processor#use()
Adds a plugin to be used as a CSS processor.
PostCSS plugin can be in 4 formats:
- A plugin in
Plugin
format. - A plugin creator function with
pluginCreator.postcss = true
. PostCSS will call this function without argument to get plugin. - A function. PostCSS will pass the function a @{link Root}
as the first argument and current
Result
instance as the second. - Another
Processor
instance. PostCSS will copy plugins from that instance into this one.
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)
Argument | Type | Description |
---|---|---|
plugin | AcceptedPlugin | PostCSS plugin or Processor with plugins. |
Returns default
. Current processor to make methods chain.
Result
Provides the result of the PostCSS transformations.
A Result instance is returned by LazyResult#then
or Root#toResult
methods.
postcss([autoprefixer]).process(css).then(result => {
console.log(result.css)
})
const result2 = postcss.parse(css).toResult()
Result#css
A CSS string representing of Result#root
.
postcss.parse('a{}').toResult().css //=> "a{}"
Type: string.
Result#lastPlugin
Last runned PostCSS plugin.
Type: Plugin | TransformCallback.
Result#map
An instance of SourceMapGenerator
class from the source-map
library,
representing changes to the Result#root
instance.
result.map.toJSON() //=> { version: 3, file: 'a.css', … }
if (result.map) {
fs.writeFileSync(result.opts.to + '.map', result.map.toString())
}
Type: SourceMap.
Result#messages
Contains messages from plugins (e.g., warnings or custom messages). Each message should have type and plugin properties.
AtRule: {
import: (atRule, { result }) {
const importedFile = parseImport(atRule)
result.messages.push({
type: 'dependency',
plugin: 'postcss-import',
file: importedFile,
parent: result.opts.from
})
}
}
Type: Message[].
Result#opts
Options from the Processor#process
or Root#toResult
call
that produced this Result instance.]
root.toResult(opts).opts === opts
Type: ResultOptions.
Result#processor
The Processor instance used for this transformation.
for (const plugin of result.processor.plugins) {
if (plugin.postcssPlugin === 'postcss-bad') {
throw 'postcss-good is incompatible with postcss-bad'
}
})
Type: default.
Result#root
Root node after all transformations.
root.toResult().root === root
Type: default | default.
Result#content
An alias for the Result#css
property.
Use it with syntaxes that generate non-CSS output.
result.css === result.content
Result#toString()
Returns for Result#css
content.
result + '' === result.css
Argument | Type |
---|
Returns string
. String representing of Result#root
.
Result#warn()
Creates an instance of Warning
and adds it to Result#messages
.
if (decl.important) {
result.warn('Avoid !important', { node: decl, word: '!important' })
}
Argument | Type |
---|---|
message | string |
options | WarningOptions |
Returns default
. Created warning.
Result#warnings()
Returns warnings from plugins. Filters Warning
instances
from Result#messages
.
result.warnings().forEach(warn => {
console.warn(warn.toString())
})
Argument | Type |
---|
Returns default[]
. Warnings from plugins.
Root
Represents a CSS file and contains all its parsed nodes.
const root = postcss.parse('a{color:black} b{z-index:2}')
root.type //=> 'root'
root.nodes.length //=> 2
Root#nodes
An array containing the container’s children.
const root = postcss.parse('a { color: black }')
root.nodes.length //=> 1
root.nodes[0].selector //=> 'a'
root.nodes[0].nodes[0].prop //=> 'color'
Type: ChildNode[].
Root#parent
The node’s parent node.
root.nodes[0].parent === root
Type: default.
Root#raws
Information to generate byte-to-byte equal node string as it was in the origin input.
Every parser saves its own properties, but the default CSS parser uses:
before
: the space symbols before the node. It also stores*
and_
symbols before the declaration (IE hack).after
: the space symbols after the last child of the node to the end of the node.between
: the symbols between the property and value for declarations, selector and{
for rules, or last parameter and{
for at-rules.semicolon
: contains true if the last child has an (optional) semicolon.afterName
: the space between the at-rule name and its parameters.left
: the space symbols between/*
and the comment’s text.right
: the space symbols between the comment’s text and */.important
: the content of the important statement, if it is not just!important
.
PostCSS cleans selectors, declaration values and at-rule parameters from comments and extra spaces, but it stores origin content in raws properties. As such, if you don’t change a declaration’s value, PostCSS will use the raw value with comments.
const root = postcss.parse('a {\n color:black\n}')
root.first.first.raws //=> { before: '\n ', between: ':' }
Type: RootRaws.
Root#source
The input source of the node.
The property is used in source map generation.
If you create a node manually (e.g., with postcss.decl()
),
that node will not have a source
property and will be absent
from the source map. For this reason, the plugin developer should
consider cloning nodes to create new ones (in which case the new node’s
source will reference the original, cloned node) or setting
the source
property manually.
decl.source.input.from //=> '/home/ai/a.sass'
decl.source.start //=> { line: 10, column: 2 }
decl.source.end //=> { line: 10, column: 12 }
// Bad
const prefixed = postcss.decl({
prop: '-moz-' + decl.prop,
value: decl.value
})
// Good
const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
if (atrule.name === 'add-link') {
const rule = postcss.rule({ selector: 'a', source: atrule.source })
atrule.parent.insertBefore(atrule, rule)
}
Type: Source.
Root#type
tring representing the node’s type. Possible values are root
, atrule
,
rule
, decl
, or comment
.
new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
Type: "root".
Root#first
The container’s first child.
rule.first === rules.nodes[0]
Root#last
The container’s last child.
rule.last === rule.nodes[rule.nodes.length - 1]
Root#after()
Insert new node after current node to current node’s parent.
Just alias for node.parent.insertAfter(node, add)
.
decl.after('color: black')
Argument | Type | Description |
---|---|---|
newNode | string | ChildProps | default | default[] | New node. |
Returns default
. This node for methods chain.
Root#append()
Inserts new nodes to the end of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.append(decl1, decl2)
root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
root.append({ selector: 'a' }) // rule
rule.append({ prop: 'color', value: 'black' }) // declaration
rule.append({ text: 'Comment' }) // comment
root.append('a {}')
root.first.append('color: black; z-index: 1')
Argument | Type | Description |
---|---|---|
nodes… | (string | ChildProps | default | default[] | ChildProps[] | string[])[] | New nodes. |
Returns default
. This node for methods chain.
Root#assign()
Assigns properties to the current node.
decl.assign({ prop: 'word-wrap', value: 'break-word' })
Argument | Type | Description |
---|---|---|
overrides | object | RootProps | New properties to override the node. |
Returns default
. Current node to methods chain.
Root#before()
Insert new node before current node to current node’s parent.
Just alias for node.parent.insertBefore(node, add)
.
decl.before('content: ""')
Argument | Type | Description |
---|---|---|
newNode | string | ChildProps | default | default[] | New node. |
Returns default
. This node for methods chain.
Root#cleanRaws()
Clear the code style properties for the node and its children.
node.raws.before //=> ' '
node.cleanRaws()
node.raws.before //=> undefined
Argument | Type | Description |
---|---|---|
keepBetween | boolean | Keep the raws.between symbols. |
Root#clone()
Returns an exact clone of the node.
The resulting cloned node and its (cloned) children will retain code style properties.
decl.raws.before //=> "\n "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before //=> "\n "
cloned.toString() //=> -moz-transform: scale(0)
Argument | Type | Description |
---|---|---|
overrides | object | New properties to override in the clone. |
Returns default
. Clone of the node.
Root#cloneAfter()
Shortcut to clone the node and insert the resulting cloned node after the current node.
Argument | Type | Description |
---|---|---|
overrides | object | New properties to override in the clone. |
Returns default
. New node.
Root#cloneBefore()
Shortcut to clone the node and insert the resulting cloned node before the current node.
decl.cloneBefore({ prop: '-moz-' + decl.prop })
Argument | Type | Description |
---|---|---|
overrides | object | Mew properties to override in the clone. |
Returns default
. New node
Root#each()
Iterates through the container’s immediate children,
calling callback
for each child.
Returning false
in the callback will break iteration.
This method only iterates through the container’s immediate children.
If you need to recursively iterate through all the container’s descendant
nodes, use Container#walk
.
Unlike the for {}
-cycle or Array#forEach
this iterator is safe
if you are mutating the array of child nodes during iteration.
PostCSS will adjust the current index to match the mutations.
const root = postcss.parse('a { color: black; z-index: 1 }')
const rule = root.first
for (const decl of rule.nodes) {
decl.cloneBefore({ prop: '-webkit-' + decl.prop })
// Cycle will be infinite, because cloneBefore moves the current node
// to the next index
}
rule.each(decl => {
decl.cloneBefore({ prop: '-webkit-' + decl.prop })
// Will be executed only for color and z-index
})
Argument | Type | Description |
---|---|---|
callback | (node: ChildNode, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Root#error()
Returns a CssSyntaxError
instance containing the original position
of the node in the source, showing line and column numbers and also
a small excerpt to facilitate debugging.
If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).
This method produces very useful error messages.
if (!variables[name]) {
throw decl.error(`Unknown variable ${name}`, { word: name })
// CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
// color: $black
// a
// ^
// background: white
}
Argument | Type | Description |
---|---|---|
message | string | Error description. |
options | NodeErrorOptions |
Returns default
. Error object to throw it.
Root#every()
Returns true
if callback returns true
for all of the container’s children.
const noPrefixes = rule.every(i => i.prop[0] !== '-')
Argument | Type | Description |
---|---|---|
condition | (node: ChildNode, index: number, nodes: ChildNode[]) => boolean | Iterator returns true or false. |
Returns boolean
. Is every child pass condition.
Root#index()
Returns a child
’s index within the Container#nodes
array.
rule.index( rule.nodes[2] ) //=> 2
Argument | Type | Description |
---|---|---|
child | number | ChildNode | Child of the current container. |
Returns number
. Child index.
Root#insertAfter()
Insert new node after old node within the container.
Argument | Type | Description |
---|---|---|
oldNode | number | ChildNode | Child or child’s index. |
newNode | string | ChildNode | ChildProps | ChildNode[] | ChildProps[] | string[] | New node. |
Returns default
. This node for methods chain.
Root#insertBefore()
Insert new node before old node within the container.
rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
Argument | Type | Description |
---|---|---|
oldNode | number | ChildNode | Child or child’s index. |
newNode | string | ChildNode | ChildProps | ChildNode[] | ChildProps[] | string[] | New node. |
Returns default
. This node for methods chain.
Root#next()
Returns the next child of the node’s parent.
Returns undefined
if the current node is the last child.
if (comment.text === 'delete next') {
const next = comment.next()
if (next) {
next.remove()
}
}
Argument | Type |
---|
Returns ChildNode
. Next node.
Root#positionBy()
Get the position for a word or an index inside the node.
Argument | Type | Description |
---|---|---|
opts | Pick<WarningOptions, "word" | "index"> | Options. |
Returns Position
. Position.
Root#positionInside()
Convert string index to line/column.
Argument | Type | Description |
---|---|---|
index | number | The symbol number in the node’s string. |
Returns Position
. Symbol position in file.
Root#prepend()
Inserts new nodes to the start of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.prepend(decl1, decl2)
root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
root.append({ selector: 'a' }) // rule
rule.append({ prop: 'color', value: 'black' }) // declaration
rule.append({ text: 'Comment' }) // comment
root.append('a {}')
root.first.append('color: black; z-index: 1')
Argument | Type | Description |
---|---|---|
nodes… | (string | ChildProps | default | default[] | ChildProps[] | string[])[] | New nodes. |
Returns default
. This node for methods chain.
Root#prev()
Returns the previous child of the node’s parent.
Returns undefined
if the current node is the first child.
const annotation = decl.prev()
if (annotation.type === 'comment') {
readAnnotation(annotation.text)
}
Argument | Type |
---|
Returns ChildNode
. Previous node.
Root#push()
Add child to the end of the node.
rule.push(new Declaration({ prop: 'color', value: 'black' }))
Argument | Type | Description |
---|---|---|
child | ChildNode | New node. |
Returns default
. This node for methods chain.
Root#rangeBy()
Get the range for a word or start and end index inside the node. The start index is inclusive; the end index is exclusive.
Argument | Type | Description |
---|---|---|
opts | Pick<WarningOptions, "word" | "index" | "endIndex"> | Options. |
Returns Range
. Range.
Root#raw()
Returns a Node#raws
value. If the node is missing
the code style property (because the node was manually built or cloned),
PostCSS will try to autodetect the code style property by looking
at other nodes in the tree.
const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
Argument | 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. |
Returns string
. Code style value.
Root#remove()
Removes the node from its parent and cleans the parent properties from the node and its children.
if (decl.prop.match(/^-webkit-/)) {
decl.remove()
}
Argument | Type |
---|
Returns default
. Node to make calls chain.
Root#removeAll()
Removes all children from the container and cleans their parent properties.
rule.removeAll()
rule.nodes.length //=> 0
Argument | Type |
---|
Returns default
. This node for methods chain.
Root#removeChild()
Removes node from the container and cleans the parent properties from the node and its children.
rule.nodes.length //=> 5
rule.removeChild(decl)
rule.nodes.length //=> 4
decl.parent //=> undefined
Argument | Type | Description |
---|---|---|
child | number | ChildNode | Child or child’s index. |
Returns default
. This node for methods chain.
Root#replaceValues()
Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.
This method is useful if you are using a custom unit or function and need to iterate through all values.
root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
return 15 * parseInt(string) + 'px'
})
Argument | Type | Description |
---|---|---|
pattern | string | RegExp | Replace pattern. |
options | ValueOptions | |
replaced | string | (substring: string, args: any[]) => string |
Argument | Type | Description |
---|---|---|
pattern | string | RegExp | Replace pattern. |
replaced | string | (substring: string, args: any[]) => string |
Returns default
. This node for methods chain.
Root#replaceWith()
Inserts node(s) before the current node and removes the current node.
AtRule: {
mixin: atrule => {
atrule.replaceWith(mixinRules[atrule.params])
}
}
Argument | Type | Description |
---|---|---|
nodes… | (ChildNode | ChildProps | ChildNode[] | ChildProps[])[] | Mode(s) to replace current one. |
Returns default
. Current node to methods chain.
Root#root()
Finds the Root instance of the node’s tree.
root.nodes[0].nodes[0].root() === root
Argument | Type |
---|
Returns default
. Root parent.
Root#some()
Returns true
if callback returns true
for (at least) one
of the container’s children.
const hasPrefix = rule.some(i => i.prop[0] === '-')
Argument | Type | Description |
---|---|---|
condition | (node: ChildNode, index: number, nodes: ChildNode[]) => boolean | Iterator returns true or false. |
Returns boolean
. Is some child pass condition.
Root#toJSON()
Fix circular links on JSON.stringify()
.
Argument | Type |
---|
Returns object
. Cleaned object.
Root#toResult()
Returns a Result
instance representing the root’s CSS.
const root1 = postcss.parse(css1, { from: 'a.css' })
const root2 = postcss.parse(css2, { from: 'b.css' })
root1.append(root2)
const result = root1.toResult({ to: 'all.css', map: true })
Argument | Type |
---|---|
options | ProcessOptions |
Returns default
. Result with current root’s CSS.
Root#toString()
Returns a CSS string representing the node.
new Rule({ selector: 'a' }).toString() //=> "a {}"
Argument | Type | Description |
---|---|---|
stringifier | Stringifier | Syntax | A syntax to use in string generation. |
Returns string
. CSS string of this node.
Root#walk()
Traverses the container’s descendant nodes, calling callback for each node.
Like container.each(), this method is safe to use if you are mutating arrays during iteration.
If you only need to iterate through the container’s immediate children,
use Container#each
.
root.walk(node => {
// Traverses all descendant nodes.
})
Argument | Type | Description |
---|---|---|
callback | (node: ChildNode, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Root#walkAtRules()
Traverses the container’s descendant nodes, calling callback for each at-rule node.
If you pass a filter, iteration will only happen over at-rules that have matching names.
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
root.walkAtRules(rule => {
if (isOld(rule.name)) rule.remove()
})
let first = false
root.walkAtRules('charset', rule => {
if (!first) {
first = true
} else {
rule.remove()
}
})
Argument | Type | Description |
---|---|---|
nameFilter | string | RegExp | |
callback | (atRule: default, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Root#walkComments()
Traverses the container’s descendant nodes, calling callback for each comment node.
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
root.walkComments(comment => {
comment.remove()
})
Argument | Type | Description |
---|---|---|
callback | (comment: default, indexed: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Root#walkDecls()
Traverses the container’s descendant nodes, calling callback for each declaration node.
If you pass a filter, iteration will only happen over declarations with matching properties.
root.walkDecls(decl => {
checkPropertySupport(decl.prop)
})
root.walkDecls('border-radius', decl => {
decl.remove()
})
root.walkDecls(/^background/, decl => {
decl.value = takeFirstColorFromGradient(decl.value)
})
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
Argument | Type | Description |
---|---|---|
propFilter | string | RegExp | |
callback | (decl: default, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Root#walkRules()
Traverses the container’s descendant nodes, calling callback for each rule node.
If you pass a filter, iteration will only happen over rules with matching selectors.
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
const selectors = []
root.walkRules(rule => {
selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
Argument | Type | Description |
---|---|---|
selectorFilter | string | RegExp | |
callback | (rule: default, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Root#warn()
This method is provided as a convenience wrapper for Result#warn
.
Declaration: {
bad: (decl, { result }) => {
decl.warn(result, 'Deprecated property bad')
}
}
Argument | Type | Description |
---|---|---|
result | default | The Result instance that will receive the warning. |
text | string | Warning message. |
opts | WarningOptions | Warning Options. |
Returns default
. Created warning object.
Rule
Represents a CSS rule: a selector followed by a declaration block.
Once (root, { Rule }) {
let a = new Rule({ selector: 'a' })
a.append(…)
root.append(a)
}
const root = postcss.parse('a{}')
const rule = root.first
rule.type //=> 'rule'
rule.toString() //=> 'a{}'
Rule#nodes
An array containing the container’s children.
const root = postcss.parse('a { color: black }')
root.nodes.length //=> 1
root.nodes[0].selector //=> 'a'
root.nodes[0].nodes[0].prop //=> 'color'
Type: ChildNode[].
Rule#parent
The node’s parent node.
root.nodes[0].parent === root
Type: default<ChildNode>.
Rule#raws
Information to generate byte-to-byte equal node string as it was in the origin input.
Every parser saves its own properties, but the default CSS parser uses:
before
: the space symbols before the node. It also stores*
and_
symbols before the declaration (IE hack).after
: the space symbols after the last child of the node to the end of the node.between
: the symbols between the property and value for declarations, selector and{
for rules, or last parameter and{
for at-rules.semicolon
: contains true if the last child has an (optional) semicolon.afterName
: the space between the at-rule name and its parameters.left
: the space symbols between/*
and the comment’s text.right
: the space symbols between the comment’s text and */.important
: the content of the important statement, if it is not just!important
.
PostCSS cleans selectors, declaration values and at-rule parameters from comments and extra spaces, but it stores origin content in raws properties. As such, if you don’t change a declaration’s value, PostCSS will use the raw value with comments.
const root = postcss.parse('a {\n color:black\n}')
root.first.first.raws //=> { before: '\n ', between: ':' }
Type: RuleRaws.
Rule#selector
The rule’s full selector represented as a string.
const root = postcss.parse('a, b { }')
const rule = root.first
rule.selector //=> 'a, b'
Type: string.
Rule#selectors
An array containing the rule’s individual selectors. Groups of selectors are split at commas.
const root = postcss.parse('a, b { }')
const rule = root.first
rule.selector //=> 'a, b'
rule.selectors //=> ['a', 'b']
rule.selectors = ['a', 'strong']
rule.selector //=> 'a, strong'
Type: string[].
Rule#source
The input source of the node.
The property is used in source map generation.
If you create a node manually (e.g., with postcss.decl()
),
that node will not have a source
property and will be absent
from the source map. For this reason, the plugin developer should
consider cloning nodes to create new ones (in which case the new node’s
source will reference the original, cloned node) or setting
the source
property manually.
decl.source.input.from //=> '/home/ai/a.sass'
decl.source.start //=> { line: 10, column: 2 }
decl.source.end //=> { line: 10, column: 12 }
// Bad
const prefixed = postcss.decl({
prop: '-moz-' + decl.prop,
value: decl.value
})
// Good
const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
if (atrule.name === 'add-link') {
const rule = postcss.rule({ selector: 'a', source: atrule.source })
atrule.parent.insertBefore(atrule, rule)
}
Type: Source.
Rule#type
tring representing the node’s type. Possible values are root
, atrule
,
rule
, decl
, or comment
.
new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
Type: "rule".
Rule#first
The container’s first child.
rule.first === rules.nodes[0]
Rule#last
The container’s last child.
rule.last === rule.nodes[rule.nodes.length - 1]
Rule#after()
Insert new node after current node to current node’s parent.
Just alias for node.parent.insertAfter(node, add)
.
decl.after('color: black')
Argument | Type | Description |
---|---|---|
newNode | string | ChildProps | default | default[] | New node. |
Returns default
. This node for methods chain.
Rule#append()
Inserts new nodes to the end of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.append(decl1, decl2)
root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
root.append({ selector: 'a' }) // rule
rule.append({ prop: 'color', value: 'black' }) // declaration
rule.append({ text: 'Comment' }) // comment
root.append('a {}')
root.first.append('color: black; z-index: 1')
Argument | Type | Description |
---|---|---|
nodes… | (string | ChildProps | default | default[] | ChildProps[] | string[])[] | New nodes. |
Returns default
. This node for methods chain.
Rule#assign()
Assigns properties to the current node.
decl.assign({ prop: 'word-wrap', value: 'break-word' })
Argument | Type | Description |
---|---|---|
overrides | object | RuleProps | New properties to override the node. |
Returns default
. Current node to methods chain.
Rule#before()
Insert new node before current node to current node’s parent.
Just alias for node.parent.insertBefore(node, add)
.
decl.before('content: ""')
Argument | Type | Description |
---|---|---|
newNode | string | ChildProps | default | default[] | New node. |
Returns default
. This node for methods chain.
Rule#cleanRaws()
Clear the code style properties for the node and its children.
node.raws.before //=> ' '
node.cleanRaws()
node.raws.before //=> undefined
Argument | Type | Description |
---|---|---|
keepBetween | boolean | Keep the raws.between symbols. |
Rule#clone()
Returns an exact clone of the node.
The resulting cloned node and its (cloned) children will retain code style properties.
decl.raws.before //=> "\n "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before //=> "\n "
cloned.toString() //=> -moz-transform: scale(0)
Argument | Type | Description |
---|---|---|
overrides | Partial<RuleProps> | New properties to override in the clone. |
Returns default
. Clone of the node.
Rule#cloneAfter()
Shortcut to clone the node and insert the resulting cloned node after the current node.
Argument | Type | Description |
---|---|---|
overrides | Partial<RuleProps> | New properties to override in the clone. |
Returns default
. New node.
Rule#cloneBefore()
Shortcut to clone the node and insert the resulting cloned node before the current node.
decl.cloneBefore({ prop: '-moz-' + decl.prop })
Argument | Type | Description |
---|---|---|
overrides | Partial<RuleProps> | Mew properties to override in the clone. |
Returns default
. New node
Rule#each()
Iterates through the container’s immediate children,
calling callback
for each child.
Returning false
in the callback will break iteration.
This method only iterates through the container’s immediate children.
If you need to recursively iterate through all the container’s descendant
nodes, use Container#walk
.
Unlike the for {}
-cycle or Array#forEach
this iterator is safe
if you are mutating the array of child nodes during iteration.
PostCSS will adjust the current index to match the mutations.
const root = postcss.parse('a { color: black; z-index: 1 }')
const rule = root.first
for (const decl of rule.nodes) {
decl.cloneBefore({ prop: '-webkit-' + decl.prop })
// Cycle will be infinite, because cloneBefore moves the current node
// to the next index
}
rule.each(decl => {
decl.cloneBefore({ prop: '-webkit-' + decl.prop })
// Will be executed only for color and z-index
})
Argument | Type | Description |
---|---|---|
callback | (node: ChildNode, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Rule#error()
Returns a CssSyntaxError
instance containing the original position
of the node in the source, showing line and column numbers and also
a small excerpt to facilitate debugging.
If present, an input source map will be used to get the original position of the source, even from a previous compilation step (e.g., from Sass compilation).
This method produces very useful error messages.
if (!variables[name]) {
throw decl.error(`Unknown variable ${name}`, { word: name })
// CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
// color: $black
// a
// ^
// background: white
}
Argument | Type | Description |
---|---|---|
message | string | Error description. |
options | NodeErrorOptions |
Returns default
. Error object to throw it.
Rule#every()
Returns true
if callback returns true
for all of the container’s children.
const noPrefixes = rule.every(i => i.prop[0] !== '-')
Argument | Type | Description |
---|---|---|
condition | (node: ChildNode, index: number, nodes: ChildNode[]) => boolean | Iterator returns true or false. |
Returns boolean
. Is every child pass condition.
Rule#index()
Returns a child
’s index within the Container#nodes
array.
rule.index( rule.nodes[2] ) //=> 2
Argument | Type | Description |
---|---|---|
child | number | ChildNode | Child of the current container. |
Returns number
. Child index.
Rule#insertAfter()
Insert new node after old node within the container.
Argument | Type | Description |
---|---|---|
oldNode | number | ChildNode | Child or child’s index. |
newNode | string | ChildNode | ChildProps | ChildNode[] | ChildProps[] | string[] | New node. |
Returns default
. This node for methods chain.
Rule#insertBefore()
Insert new node before old node within the container.
rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
Argument | Type | Description |
---|---|---|
oldNode | number | ChildNode | Child or child’s index. |
newNode | string | ChildNode | ChildProps | ChildNode[] | ChildProps[] | string[] | New node. |
Returns default
. This node for methods chain.
Rule#next()
Returns the next child of the node’s parent.
Returns undefined
if the current node is the last child.
if (comment.text === 'delete next') {
const next = comment.next()
if (next) {
next.remove()
}
}
Argument | Type |
---|
Returns ChildNode
. Next node.
Rule#positionBy()
Get the position for a word or an index inside the node.
Argument | Type | Description |
---|---|---|
opts | Pick<WarningOptions, "word" | "index"> | Options. |
Returns Position
. Position.
Rule#positionInside()
Convert string index to line/column.
Argument | Type | Description |
---|---|---|
index | number | The symbol number in the node’s string. |
Returns Position
. Symbol position in file.
Rule#prepend()
Inserts new nodes to the start of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.prepend(decl1, decl2)
root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
root.append({ selector: 'a' }) // rule
rule.append({ prop: 'color', value: 'black' }) // declaration
rule.append({ text: 'Comment' }) // comment
root.append('a {}')
root.first.append('color: black; z-index: 1')
Argument | Type | Description |
---|---|---|
nodes… | (string | ChildProps | default | default[] | ChildProps[] | string[])[] | New nodes. |
Returns default
. This node for methods chain.
Rule#prev()
Returns the previous child of the node’s parent.
Returns undefined
if the current node is the first child.
const annotation = decl.prev()
if (annotation.type === 'comment') {
readAnnotation(annotation.text)
}
Argument | Type |
---|
Returns ChildNode
. Previous node.
Rule#push()
Add child to the end of the node.
rule.push(new Declaration({ prop: 'color', value: 'black' }))
Argument | Type | Description |
---|---|---|
child | ChildNode | New node. |
Returns default
. This node for methods chain.
Rule#rangeBy()
Get the range for a word or start and end index inside the node. The start index is inclusive; the end index is exclusive.
Argument | Type | Description |
---|---|---|
opts | Pick<WarningOptions, "word" | "index" | "endIndex"> | Options. |
Returns Range
. Range.
Rule#raw()
Returns a Node#raws
value. If the node is missing
the code style property (because the node was manually built or cloned),
PostCSS will try to autodetect the code style property by looking
at other nodes in the tree.
const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
Argument | 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. |
Returns string
. Code style value.
Rule#remove()
Removes the node from its parent and cleans the parent properties from the node and its children.
if (decl.prop.match(/^-webkit-/)) {
decl.remove()
}
Argument | Type |
---|
Returns default
. Node to make calls chain.
Rule#removeAll()
Removes all children from the container and cleans their parent properties.
rule.removeAll()
rule.nodes.length //=> 0
Argument | Type |
---|
Returns default
. This node for methods chain.
Rule#removeChild()
Removes node from the container and cleans the parent properties from the node and its children.
rule.nodes.length //=> 5
rule.removeChild(decl)
rule.nodes.length //=> 4
decl.parent //=> undefined
Argument | Type | Description |
---|---|---|
child | number | ChildNode | Child or child’s index. |
Returns default
. This node for methods chain.
Rule#replaceValues()
Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.
This method is useful if you are using a custom unit or function and need to iterate through all values.
root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
return 15 * parseInt(string) + 'px'
})
Argument | Type | Description |
---|---|---|
pattern | string | RegExp | Replace pattern. |
options | ValueOptions | |
replaced | string | (substring: string, args: any[]) => string |
Argument | Type | Description |
---|---|---|
pattern | string | RegExp | Replace pattern. |
replaced | string | (substring: string, args: any[]) => string |
Returns default
. This node for methods chain.
Rule#replaceWith()
Inserts node(s) before the current node and removes the current node.
AtRule: {
mixin: atrule => {
atrule.replaceWith(mixinRules[atrule.params])
}
}
Argument | Type | Description |
---|---|---|
nodes… | (ChildNode | ChildProps | ChildNode[] | ChildProps[])[] | Mode(s) to replace current one. |
Returns default
. Current node to methods chain.
Rule#root()
Finds the Root instance of the node’s tree.
root.nodes[0].nodes[0].root() === root
Argument | Type |
---|
Returns default
. Root parent.
Rule#some()
Returns true
if callback returns true
for (at least) one
of the container’s children.
const hasPrefix = rule.some(i => i.prop[0] === '-')
Argument | Type | Description |
---|---|---|
condition | (node: ChildNode, index: number, nodes: ChildNode[]) => boolean | Iterator returns true or false. |
Returns boolean
. Is some child pass condition.
Rule#toJSON()
Fix circular links on JSON.stringify()
.
Argument | Type |
---|
Returns object
. Cleaned object.
Rule#toString()
Returns a CSS string representing the node.
new Rule({ selector: 'a' }).toString() //=> "a {}"
Argument | Type | Description |
---|---|---|
stringifier | Stringifier | Syntax | A syntax to use in string generation. |
Returns string
. CSS string of this node.
Rule#walk()
Traverses the container’s descendant nodes, calling callback for each node.
Like container.each(), this method is safe to use if you are mutating arrays during iteration.
If you only need to iterate through the container’s immediate children,
use Container#each
.
root.walk(node => {
// Traverses all descendant nodes.
})
Argument | Type | Description |
---|---|---|
callback | (node: ChildNode, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Rule#walkAtRules()
Traverses the container’s descendant nodes, calling callback for each at-rule node.
If you pass a filter, iteration will only happen over at-rules that have matching names.
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
root.walkAtRules(rule => {
if (isOld(rule.name)) rule.remove()
})
let first = false
root.walkAtRules('charset', rule => {
if (!first) {
first = true
} else {
rule.remove()
}
})
Argument | Type | Description |
---|---|---|
nameFilter | string | RegExp | |
callback | (atRule: default, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Rule#walkComments()
Traverses the container’s descendant nodes, calling callback for each comment node.
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
root.walkComments(comment => {
comment.remove()
})
Argument | Type | Description |
---|---|---|
callback | (comment: default, indexed: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Rule#walkDecls()
Traverses the container’s descendant nodes, calling callback for each declaration node.
If you pass a filter, iteration will only happen over declarations with matching properties.
root.walkDecls(decl => {
checkPropertySupport(decl.prop)
})
root.walkDecls('border-radius', decl => {
decl.remove()
})
root.walkDecls(/^background/, decl => {
decl.value = takeFirstColorFromGradient(decl.value)
})
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
Argument | Type | Description |
---|---|---|
propFilter | string | RegExp | |
callback | (decl: default, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Rule#walkRules()
Traverses the container’s descendant nodes, calling callback for each rule node.
If you pass a filter, iteration will only happen over rules with matching selectors.
Like Container#each
, this method is safe
to use if you are mutating arrays during iteration.
const selectors = []
root.walkRules(rule => {
selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
Argument | Type | Description |
---|---|---|
selectorFilter | string | RegExp | |
callback | (rule: default, index: number) => false | void | Iterator receives each node and index. |
Returns void | false
. Returns false
if iteration was broke.
Rule#warn()
This method is provided as a convenience wrapper for Result#warn
.
Declaration: {
bad: (decl, { result }) => {
decl.warn(result, 'Deprecated property bad')
}
}
Argument | Type | Description |
---|---|---|
result | default | The Result instance that will receive the warning. |
text | string | Warning message. |
opts | WarningOptions | Warning Options. |
Returns default
. Created warning object.
Stringifier
Stringifier#builder
Type: Builder.
Stringifier#atrule()
Argument | Type |
---|---|
node | default |
semicolon | boolean |
Stringifier#beforeAfter()
Argument | Type |
---|---|
node | AnyNode |
detect | "before" | "after" |
Returns string
.
Stringifier#block()
Argument | Type |
---|---|
node | AnyNode |
start | string |
Stringifier#body()
Argument | Type |
---|---|
node | default<ChildNode> |
Stringifier#comment()
Argument | Type |
---|---|
node | default |
Stringifier#decl()
Argument | Type |
---|---|
node | default |
semicolon | boolean |
Stringifier#document()
Argument | Type |
---|---|
node | default |
Stringifier#raw()
Argument | Type |
---|---|
node | AnyNode |
own | string |
detect | string |
Returns string
.
Stringifier#rawBeforeClose()
Argument | Type |
---|---|
root | default |
Returns string
.
Stringifier#rawBeforeComment()
Argument | Type |
---|---|
root | default |
node | default |
Returns string
.
Stringifier#rawBeforeDecl()
Argument | Type |
---|---|
root | default |
node | default |
Returns string
.
Stringifier#rawBeforeOpen()
Argument | Type |
---|---|
root | default |
Returns string
.
Stringifier#rawBeforeRule()
Argument | Type |
---|---|
root | default |
Returns string
.
Stringifier#rawColon()
Argument | Type |
---|---|
root | default |
Returns string
.
Stringifier#rawEmptyBody()
Argument | Type |
---|---|
root | default |
Returns string
.
Stringifier#rawIndent()
Argument | Type |
---|---|
root | default |
Returns string
.
Stringifier#rawSemicolon()
Argument | Type |
---|---|
root | default |
Returns boolean
.
Stringifier#rawValue()
Argument | Type |
---|---|
node | AnyNode |
prop | string |
Returns string
.
Stringifier#root()
Argument | Type |
---|---|
node | default |
Stringifier#rule()
Argument | Type |
---|---|
node | default |
Stringifier#stringify()
Argument | Type |
---|---|
node | AnyNode |
semicolon | boolean |
Warning
Represents a plugin’s warning. It can be created using Node#warn
.
if (decl.important) {
decl.warn(result, 'Avoid !important', { word: '!important' })
}
Warning#column
Column for inclusive start position in the input file with this warning’s source.
warning.column //=> 6
Type: number.
Warning#endColumn
Column for exclusive end position in the input file with this warning’s source.
warning.endColumn //=> 4
Type: number.
Warning#endLine
Line for exclusive end position in the input file with this warning’s source.
warning.endLine //=> 6
Type: number.
Warning#line
Line for inclusive start position in the input file with this warning’s source.
warning.line //=> 5
Type: number.
Warning#node
Contains the CSS node that caused the warning.
warning.node.toString() //=> 'color: white !important'
Type: default.
Warning#plugin
The name of the plugin that created this warning.
When you call Node#warn
it will fill this property automatically.
warning.plugin //=> 'postcss-important'
Type: string.
Warning#text
The warning message.
warning.text //=> 'Try to avoid !important'
Type: string.
Warning#type
Type to filter warnings from Result#messages
.
Always equal to "warning"
.
Type: "warning".
Warning#toString()
Returns a warning position and message.
warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'
Argument | Type |
---|
Returns string
. Warning position and message.
AcceptedPlugin
Type: Plugin | PluginCreator<any> | OldPlugin<any> | TransformCallback | { postcss: TransformCallback | default } | default.
AnyNode
Type: default | default | default | default | default | default.
AnyNode
AtRule
AtRuleProps
Property | Type | Description |
---|---|---|
name | string | Name of the at-rule. |
nodes | (ChildNode | ChildProps)[] | |
params | string | number | Parameters following the name of the at-rule. |
raws | AtRuleRaws | Information used to generate byte-to-byte equal node string as it was in the origin input. |
source | Source |
AtRuleProps
AtRuleRaws
Property | Type | Description |
---|---|---|
after | string | The space symbols after the last child of the node to the end of the node. |
afterName | string | The space between the at-rule name and its parameters. |
before | string | The space symbols before the node. It also stores *
and _ symbols before the declaration (IE hack). |
between | string | The symbols between the last parameter and { for rules. |
params | { raw: string, value: string } | The rule’s selector with comments. |
semicolon | boolean | Contains true if the last child has an (optional) semicolon. |
Builder
Argument | Type |
---|---|
part | string |
node | AnyNode |
type | "start" | "end" |
ChildNode
Type: default.
ChildNode
Type: default | default | default | default.
ChildNode
ChildProps
Type: RootProps.
ChildProps
Type: AtRuleProps | RuleProps | DeclarationProps | CommentProps.
ChildProps
Comment
CommentProps
Property | Type | Description |
---|---|---|
raws | CommentRaws | Information used to generate byte-to-byte equal node string as it was in the origin input. |
source | Source | |
text | string | Content of the comment. |
CommentProps
CommentRaws
Property | Type | Description |
---|---|---|
before | string | The space symbols before the node. |
left | string | The space symbols between /* and the comment’s text. |
right | string | The space symbols between the comment’s text. |
Container
ContainerProps
Property | Type |
---|---|
nodes | (ChildNode | ChildProps)[] |
source | Source |
ContainerProps
CssSyntaxError
Declaration
DeclarationProps
Property | Type | Description |
---|---|---|
important | boolean | Whether the declaration has an !important annotation. |
prop | string | Name of the declaration. |
raws | DeclarationRaws | Information used to generate byte-to-byte equal node string as it was in the origin input. |
value | string | Value of the declaration. |
DeclarationProps
DeclarationRaws
Property | Type | Description |
---|---|---|
before | string | The space symbols before the node. It also stores *
and _ symbols before the declaration (IE hack). |
between | string | The symbols between the property and value for declarations. |
important | string | The content of the important statement, if it is not just !important . |
value | { raw: string, value: string } | Declaration value with comments. |
Document
DocumentProps
Property | Type | Description |
---|---|---|
nodes | default[] | |
raws | Record<string, any> | Information to generate byte-to-byte equal node string as it was in the origin input. Every parser saves its own properties. |
source | Source |
DocumentProps
FilePosition
Property | Type | Description |
---|---|---|
column | number | Column of inclusive start position in source file. |
endColumn | number | Column of exclusive end position in source file. |
endLine | number | Line of exclusive end position in source file. |
file | string | Absolute path to the source file. |
line | number | Line of inclusive start position in source file. |
source | string | Source code. |
url | string | URL for the source file. |
FilePosition
Helpers
Type: object & Postcss.
Input
JSONHydrator
Argument | Type |
---|---|
data | object[] |
Argument | Type |
---|---|
data | object |
Returns default[]
.
LazyResult
Message
Message
Property | Type | Description |
---|---|---|
plugin | string | Source PostCSS plugin name. |
type | string | Message type. |
Node
NodeErrorOptions
Property | Type | Description |
---|---|---|
endIndex | number | An ending index inside a node's string that should be highlighted as source of error. |
index | number | An index inside a node's string that should be highlighted as source of error. |
plugin | string | Plugin name that created this error. PostCSS will set it automatically. |
word | string | A word inside a node's string, that should be highlighted as source of error. |
NodeErrorOptions
NodeProps
Property | Type |
---|---|
source | Source |
NodeProps
OldPlugin
Argument | Type |
---|---|
opts | T |
Argument | Type |
---|---|
root | default |
result | default |
Returns Transformer
.
OldPlugin#postcss
Type: Transformer.
OldPlugin#postcssPlugin
Type: string.
OldPlugin#postcssVersion
Type: string.
Parser
Argument | Type |
---|---|
css | string | { toString: () => string } |
opts | Pick<ProcessOptions, "map" | "from"> |
Returns RootNode
.
Plugin
Plugin#AtRule
Will be called on allAtRule
nodes.
Will be called again on node or children changes.
Type: AtRuleProcessor | { [name: string]: AtRuleProcessor}.
Plugin#AtRuleExit
Will be called on all AtRule
nodes, when all children will be processed.
Will be called again on node or children changes.
Type: AtRuleProcessor | { [name: string]: AtRuleProcessor}.
Plugin#Comment
Will be called on all Comment
nodes.
Will be called again on node or children changes.
Type: CommentProcessor.
Plugin#CommentExit
Will be called on all Comment
nodes after listeners
for Comment
event.
Will be called again on node or children changes.
Type: CommentProcessor.
Plugin#Declaration
Will be called on all Declaration
nodes after listeners
for Declaration
event.
Will be called again on node or children changes.
Type: DeclarationProcessor | { [prop: string]: DeclarationProcessor}.
Plugin#DeclarationExit
Will be called on all Declaration
nodes.
Will be called again on node or children changes.
Type: DeclarationProcessor | { [prop: string]: DeclarationProcessor}.
Plugin#Document
Will be called on Document
node.
Will be called again on children changes.
Type: DocumentProcessor.
Plugin#DocumentExit
Will be called on Document
node, when all children will be processed.
Will be called again on children changes.
Type: DocumentProcessor.
Plugin#Exit
Will be called when all other listeners processed the document.
This listener will not be called again.
Type: RootProcessor.
Plugin#Once
Will be called on Root
node once.
Type: RootProcessor.
Plugin#OnceExit
Will be called on Root
node once, when all children will be processed.
Type: RootProcessor.
Plugin#Root
Will be called on Root
node.
Will be called again on children changes.
Type: RootProcessor.
Plugin#RootExit
Will be called on Root
node, when all children will be processed.
Will be called again on children changes.
Type: RootProcessor.
Plugin#Rule
Will be called on all Rule
nodes.
Will be called again on node or children changes.
Type: RuleProcessor.
Plugin#RuleExit
Will be called on all Rule
nodes, when all children will be processed.
Will be called again on node or children changes.
Type: RuleProcessor.
Plugin#postcssPlugin
Type: string.
Plugin#prepare()
Argument | Type |
---|---|
result | default |
Returns Processors
.
PluginCreator
Argument | Type |
---|---|
opts | PluginOptions |
Returns default | Plugin
.
PluginCreator#postcss
Type: true.
Position
Property | Type | Description |
---|---|---|
column | number | Source line in file. In contrast to offset it starts from 1. |
line | number | Source column in file. |
offset | number | Source offset in file. It starts from 0. |
Position
ProcessOptions
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. |
map | boolean | SourceMapOptions | Source map options |
parser | Syntax | Parser<default | default> | Function to generate AST by string. |
stringifier | Stringifier | Syntax | Class to generate string by AST. |
syntax | Syntax | Object with parse and stringify. |
to | string | The path where you'll put the output CSS file. You should always set to
to generate correct source maps. |
Processor
Range
Range#end
End position, exclusive.
Type: Position.
Range#start
Start position, inclusive.
Type: Position.
RangePosition
A position that is part of a range.
Property | Type | Description |
---|---|---|
column | number | The column number in the input. |
line | number | The line number in the input. |
Result
ResultOptions
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. |
map | boolean | SourceMapOptions | Source map options |
node | default | The CSS node that was the source of the warning. |
parser | Syntax | Parser<default | default> | Function to generate AST by string. |
plugin | string | Name of plugin that created this warning. Result#warn will fill it
automatically with Plugin#postcssPlugin value. |
stringifier | Stringifier | Syntax | Class to generate string by AST. |
syntax | Syntax | Object with parse and stringify. |
to | string | The path where you'll put the output CSS file. You should always set to
to generate correct source maps. |
Root
RootProps
RootProps
Property | Type | Description |
---|---|---|
nodes | (ChildNode | ChildProps)[] | |
raws | RootRaws | Information used to generate byte-to-byte equal node string as it was in the origin input. |
source | Source |
RootRaws
Property | Type | Description |
---|---|---|
after | string | The space symbols after the last child to the end of file. |
codeAfter | string | Non-CSS code after Root , when Root is inside Document .
Experimental: some aspects of this node could change within minor
or patch version releases. |
codeBefore | string | Non-CSS code before Root , when Root is inside Document .
Experimental: some aspects of this node could change within minor
or patch version releases. |
semicolon | boolean | Is the last child has an (optional) semicolon. |
Rule
RuleProps
RuleProps
Property | Type | Description |
---|---|---|
nodes | (ChildNode | ChildProps)[] | |
raws | RuleRaws | Information used to generate byte-to-byte equal node string as it was in the origin input. |
selector | string | Selector or selectors of the rule. |
selectors | string[] | Selectors of the rule represented as an array of strings. |
source | Source |
RuleRaws
Property | Type | Description |
---|---|---|
after | string | The space symbols after the last child of the node to the end of the node. |
before | string | The space symbols before the node. It also stores *
and _ symbols before the declaration (IE hack). |
between | string | The symbols between the selector and { for rules. |
ownSemicolon | string | Contains true if there is semicolon after rule. |
selector | { raw: string, value: string } | The rule’s selector with comments. |
semicolon | boolean | Contains true if the last child has an (optional) semicolon. |
Source
Property | Type | Description |
---|---|---|
end | Position | The inclusive ending position of the node's source. |
input | default | The file source of the node. |
start | Position | The inclusive starting position of the node’s source. |
Source
SourceMap
Type: SourceMapGenerator & object.
SourceMapOptions
Property | Type | Description |
---|---|---|
absolute | boolean | Use absolute path in generated source map. |
annotation | string | boolean | (file: string, root: default) => string | 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. |
from | string | Override from in map’s sources. |
inline | boolean | 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 . |
prev | string | boolean | object | (file: string) => string | 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 . |
sourcesContent | boolean | 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. |
Stringifier
Argument | Type |
---|---|
node | AnyNode |
builder | Builder |
Syntax
Property | Type | Description |
---|---|---|
parse | Parser<default | default> | Function to generate AST by string. |
stringify | Stringifier | Class to generate string by AST. |
TransformCallback
Argument | Type |
---|---|
root | default |
result | default |
Returns void | Promise<void>
.
Transformer
Argument | Type |
---|---|
root | default |
result | default |
Returns void | Promise<void>
.
Transformer#postcssPlugin
Type: string.
Transformer#postcssVersion
Type: string.
ValueOptions
Property | Type | Description |
---|---|---|
fast | string | String that’s used to narrow down values and speed up the regexp search. |
props | string[] | An array of property names. |
Warning
WarningOptions
WarningOptions
Property | Type | Description |
---|---|---|
end | RangePosition | End position, exclusive, in CSS node string that caused the warning. |
endIndex | number | End index, exclusive, in CSS node string that caused the warning. |
index | number | Start index, inclusive, in CSS node string that caused the warning. |
node | default | CSS node that caused the warning. |
plugin | string | Name of the plugin that created this warning. Result#warn fills
this property automatically. |
start | RangePosition | Start position, inclusive, in CSS node string that caused the warning. |
word | string | Word in CSS source that caused the warning. |
comment
Argument | Type |
---|---|
defaults | CommentProps |
Returns default
.
fromJSON
Argument | Type |
---|---|
data | object[] |
Argument | Type |
---|---|
data | object |
Returns default[]
.
fromJSON
Argument | Type |
---|---|
data | object[] |
Argument | Type |
---|---|
data | object |
Returns default[]
.
list
list.comma()
Safely splits comma-separated values (such as those for transition-*
and background
properties).
Once (root, { list }) {
list.comma('black, linear-gradient(white, black)')
//=> ['black', 'linear-gradient(white, black)']
}
Argument | Type | Description |
---|---|---|
str | string | Comma-separated values. |
Returns string[]
. Split values.
list.space()
Safely splits space-separated values (such as those for background
,
border-radius
, and other shorthand properties).
Once (root, { list }) {
list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
}
Argument | Type | Description |
---|---|---|
str | string | Space-separated values. |
Returns string[]
. Split values.
list.split()
Safely splits values.
Once (root, { list }) {
list.split('1px calc(10% + 1px)', [' ', '\n', '\t']) //=> ['1px', 'calc(10% + 1px)']
}
Argument | Type | Description |
---|---|---|
string | string | separated values. |
separators | string[] | array of separators. |
last | boolean | boolean indicator. |
Returns string[]
. Split values.
parse
Argument | Type |
---|---|
css | string | { toString: () => string } |
opts | Pick<ProcessOptions, "map" | "from"> |
Returns default | default
.
stringify
Argument | Type |
---|---|
node | AnyNode |
builder | Builder |