I’ve been receiving the same question for a long time now: Should I use CloudEvents or AsyncAPI? — And my response has always been the same: it depends!
There is the belief by many people that AsyncAPI and CloudEvents are competing for the same thing. This can’t be less true, and I’d like to explain you why. Read on!
What is CloudEvents? #
From cloudevents.io:
Enter CloudEvents, a specification for describing event data in a common way. CloudEvents seeks to ease event declaration and delivery across services, platforms and beyond!
The purpose of CloudEvents is to establish a common format for event data description. And it makes a lot of sense when you realize they are part of the CNCF’s Serverless Working Group.
If you are doing serverless or FaaS (Function as a Service), then CloudEvents is your best friend because the event is the only information you will have in your function during runtime. No topics or channels, no servers, no subscribers. Just the event and some extra information you may need to make your function work.
CloudEvents is focused on the event and defines an envelope for your application’s data. See an example from their repo:
{
"specversion" : "0.2",
"type" : "com.github.pull.create",
"source" : "https://github.com/cloudevents/spec/pull/123",
"id" : "A234-1234-1234",
"time" : "2018-04-05T17:31:00Z",
"comexampleextension1" : "value",
"comexampleextension2" : {
"othervalue": 5
},
"contenttype" : "text/xml",
"data" : "<much wow=\"xml\"/>"
}
Here your event is actually <much wow=\"xml\"/>
and the rest is meta information about your event. This envelope is what CloudEvents defines with the purpose of making event declaration reusable across services and platforms.
What is AsyncAPI? #
From the AsyncAPI repo:
Create machine-readable definitions of your event-driven APIs.
The purpose of AsyncAPI is to provide a way for you to define how your event-driven applications (or APIs) communicate with the rest of the world. AsyncAPI is focused on the application and the channels it uses to communicate. Similar to what OpenAPI and RAML do for REST APIs. Unlike CloudEvents —who focuses on the message— AsyncAPI does not impose how your event must look like but, instead, allows you to strictly define its shape. See an example:
asyncapi: 2.0.0-rc1
id: urn:com.asyncapi.examples.user
info:
title: User service
version: 1.6.3
channels:
user/signedup:
publish:
message:
payload:
type: object
properties:
fullName:
type: string
email:
type: string
format: email
Looking at the example above, one can rapidly say this is the AsyncAPI definition of a User service, which its API version is 1.6.3 and it publishes to the user/signedup
channel an event that is an object containing two properties: fullName
and email
.
We can define the event payload but its structure is totally free and user-defined. And that’s what makes AsyncAPI so powerful! Since our event payload can be anything, it can also be a CloudEvents event.
AsyncAPI + CloudEvents #
Let’s see an example of the two combined:
asyncapi: 2.0.0-rc1
id: urn:com.asyncapi.examples.user
info:
title: User service
version: 1.6.3
channels:
user/signedup:
publish:
message:
payload:
type: object
properties:
specversion:
type: string
enum: ['0.2']
type:
type: string
example: com.github.pull.create
source:
type: string
format: uri
example: urn:com.asyncapi.examples.user
id:
type: string
example: 'A234-1234-1234'
time:
type: string
format: date-time
example: 2018-04-05T17:31:00Z
contenttype:
type: string
example: 'application/json'
data:
type: object
properties:
fullName:
type: string
email:
type: string
format: email
Looking at the example above, one can say this is the AsyncAPI definition of a User service, which its API version is 1.6.3 and it publishes to the user/signedup
channel a CloudEvents event whose data is a JSON object containing two properties: fullName
and email
.
Leveraging AsyncAPI Custom Schema Formats #
There’s only one concern with the approach above: every single CloudEvents definition is going to be exactly the same from line 11 to 33 — except for the examples that were added in this blog for clarity.
The default format for defining events (messages) in AsyncAPI 2.0 is JSON Schema. Thankfully, AsyncAPI provides a way to define events in your own custom format —like Avro and Protobuf — or a hypothetical CloudEvents one in this case. See example:
asyncapi: 2.0.0-rc1
id: urn:com.asyncapi.examples.user
info:
title: User service
version: 1.6.3
channels:
user/signedup:
publish:
message:
schemaFormat: 'application/cloudevents+json; version=0.2; charset=utf-8'
payload:
type: object
properties:
fullName:
type: string
email:
type: string
format: email
This results in a much shorter and nicer way of defining the usage of CloudEvents inside an AsyncAPI document.
Ok, it’s possible but, does it makes sense? #
It really depends on your use case but it makes sense in scenarios where some kind of FaaS is involved. Consider the following example:
Reading the diagram from the bottom up, we see an overly simplified diagram of a sign up process. The user/signedup
event flows from the REST API to the monitoring service and the FaaS API through the broker. The event could have the CloudEvents format so that both, the FaaS API and the monitoring service, understand it. Obviously, one may argue that the Faas API could be wrapping the event data in CloudEvents format and leave the rest of the events untouched, in plain JSON. Fair.
So, does it really makes sense? It certainly does in some situations. Do you have to use AsyncAPI and CloudEvents together? As always that’s up to you. You have the tools. Choose them wisely.
Conclusion #
We’ve learned how AsyncAPI differs from CloudEvents. Before I finish these lines, I’d like to make something clear again: AsyncAPI focuses on the application and how it is connected; and CloudEvents focuses on the message. Both things are compatible and complementary. Evaluate what are your needs and decide which one suits them better. There’s no one-size-fits-all solution.
I hope you learned something new, if so, please consider donating to the AsyncAPI Initiative.
Until next time! 👋


PROJECTS
Please upload layouts, links, and labels here.
LOAD SELECTION
SEARCH
SEARCH BY NAME
TAXONOMY EXPLORER
RESULTS
Start new selection Add to current selection Intersect with existing selection Subtract from existing selection SAVE


Oeiras lies 20km west of Lisbon and 10km east of Cascais.
This attractive and interesting town offers an alternative to the crowded berthing in Lisbon city itself.
Position 38º 40.36'N, 09º 19.46'W.
Clearance services are available here (24/7)
Last updated January 2016.
Approach
The harbour entrance is approximately 0.5 miles, on the east side of S. Julião beacon (0c R 5s), with a range of 14 miles, placed on a grey prismatic tower with red dome, 41 meters high.
Leading Line
The entrance is approached on a 277º course, up to the alignment of the small breakwater beacons, and then the course must be corrected to SW (nearly 225º), in such a way as to pass between the southern breakwater and the top of the pier breakwater.
Entrance
The Yachting Harbour entrance is located between the north and south jetties.
Note that the entrance here can become rough with swell from the south combined with the ebb current.
This small, purpose built marina has excellent facilities and offers a number of services useful to visiting cruisers with multi-lingual staff (English, French, German, Italian and Spanish).
The bars, restaurants and shops are just a few feet from the boats and it's a 15 minute walk in to the town (free supermarket shuttle bus).
Many small repairs can be carried out by dedicated marina staff. Use of swimming pool (April to October) and supermarket shuttle are included in the berthing fee.
There is a nice sandy beach next to the marina and several cultural events on during the year.
Last updated April 2015.


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


Your
SOUCE
Home
About us
Product
Portfolio
Contact us
Sign up
Social
media
Marketing
social media is a vast platform if you target your nich with better strategy & vision
Get Started


What's the goal of this website?
This project is an introductive tutorial to building real decentralized applications (DApps) on Ethereum. Ethereum is a decentralized platform that runs smart contracts, applications that run exactly as programmed without any possibility of downtime, censorship, fraud or third-party interference.
Why do I need to care about Ethereum, what does it offer?
With Smart contracts, Ethereum allow the management of value, possessions, and multiple other things. This project is powered by a Smart Contract that keeps track of parcels, and allow owners to exchange them, modify them, or sell them.
Is this website real or just a simulation?
The website is in every point real. The pixels parcels present on the home page belong to their owner or were not acquired yet. If you own a parcel, it's yours, and nobody can take it from you. If this website was ever taken down, your parcel will still be present on the main Ethereum blockchain, and you can access to it on etherscan for example, or you can clone the github repository of this website and set it up again on your own! You'll have access to same Smart Contract that keep track of your and the others parcels.
What do I need to acquire a parcel?
A computer running Chrome or Firefox, and have the MetaMask plugin installed on them. MetaMask is a digital wallet that allow the management of Ether, the crypto-currency of Ethereum. The Ether will allow you to acquire a parcel.
How do I install MetaMask?
In order to acquire, modify, or exchange parcels, you’ll need to install MetaMask on your Chrome or Firefox browser and load it up with ether.
How do I get Ether?
If you are a U.S. citizen, you can buy ether in MetaMask.
For everyone else, you will need to purchase ether from an exchange. The easiest way is using Coinbase and then transferring the ether from your Coinbase wallet to your MetaMask wallet.
What's a token?
A token is the representation of an asset in a Smart Contract. In the case of this project, it's a non-fungible token, which means that each token is different from another one, because each parcel is unique, and have unique characteristics.
Is this all?
This FAQ, like this whole website, are still under construction. Be sure to come back a bit later when more content is added!