postcss
- Version 8.4.49
- Published
- 201 kB
- 3 dependencies
- MIT license
Install
npm i postcss
yarn add postcss
pnpm add postcss
Overview
Tool for transforming styles with JS plugins
Index
Variables
Functions
Classes
Interfaces
Type Aliases
Namespaces
postcss
- AcceptedPlugin
- AnyNode
- atRule()
- AtRule
- AtRuleProps
- Builder
- ChildNode
- ChildProps
- comment()
- Comment
- CommentProps
- Container
- ContainerProps
- CssSyntaxError
- decl()
- Declaration
- DeclarationProps
- document()
- Document
- DocumentProps
- FilePosition
- fromJSON
- Helpers
- Input
- JSONHydrator
- LazyResult
- Message
- NewChild
- Node
- NodeErrorOptions
- NodeProps
- OldPlugin
- parse
- Parser
- Plugin
- PluginCreator
- Position
- postcss()
- Postcss
- ProcessOptions
- Processor
- Result
- root()
- Root
- RootProps
- rule()
- Rule
- RuleProps
- Source
- SourceMap
- SourceMapOptions
- Stringifier
- stringify
- Syntax
- TransformCallback
- Transformer
- Warning
- WarningOptions
postcss.postcss
- AcceptedPlugin
- AnyNode
- atRule()
- AtRule
- AtRuleProps
- Builder
- ChildNode
- ChildProps
- comment()
- Comment
- CommentProps
- Container
- ContainerProps
- CssSyntaxError
- decl()
- Declaration
- DeclarationProps
- document()
- Document
- DocumentProps
- FilePosition
- fromJSON
- Helpers
- Input
- JSONHydrator
- LazyResult
- Message
- NewChild
- Node
- NodeErrorOptions
- NodeProps
- OldPlugin
- parse
- Parser
- Plugin
- PluginCreator
- Position
- postcss()
- Postcss
- ProcessOptions
- Processor
- Result
- root()
- Root
- RootProps
- rule()
- Rule
- RuleProps
- Source
- SourceMap
- SourceMapOptions
- Stringifier
- stringify
- Syntax
- TransformCallback
- Transformer
- Warning
- WarningOptions
postcss.postcss.postcss
- AcceptedPlugin
- AnyNode
- atRule()
- AtRule
- AtRuleProps
- Builder
- ChildNode
- ChildProps
- comment()
- Comment
- CommentProps
- Container
- ContainerProps
- CssSyntaxError
- decl()
- Declaration
- DeclarationProps
- document()
- Document
- DocumentProps
- FilePosition
- fromJSON
- Helpers
- Input
- JSONHydrator
- LazyResult
- Message
- NewChild
- Node
- NodeErrorOptions
- NodeProps
- OldPlugin
- parse
- Parser
- Plugin
- PluginCreator
- Position
- postcss()
- Postcss
- ProcessOptions
- Processor
- Result
- root()
- Root
- RootProps
- rule()
- Rule
- RuleProps
- Source
- SourceMap
- SourceMapOptions
- Stringifier
- stringify
- Syntax
- TransformCallback
- Transformer
- Warning
- WarningOptions
postcss.postcss.postcss.postcss
- AcceptedPlugin
- AnyNode
- atRule()
- AtRule
- AtRuleProps
- Builder
- ChildNode
- ChildProps
- comment()
- Comment
- CommentProps
- Container
- ContainerProps
- CssSyntaxError
- decl()
- Declaration
- DeclarationProps
- document()
- Document
- DocumentProps
- FilePosition
- fromJSON
- Helpers
- Input
- JSONHydrator
- LazyResult
- Message
- NewChild
- Node
- NodeErrorOptions
- NodeProps
- OldPlugin
- parse
- Parser
- Plugin
- PluginCreator
- Position
- postcss()
- Postcss
- ProcessOptions
- Processor
- Result
- root()
- Root
- RootProps
- rule()
- Rule
- RuleProps
- Source
- SourceMap
- SourceMapOptions
- Stringifier
- stringify
- Syntax
- TransformCallback
- Transformer
- Warning
- WarningOptions
postcss.postcss.postcss.postcss.postcss
- AcceptedPlugin
- AnyNode
- atRule()
- AtRule
- AtRuleProps
- Builder
- ChildNode
- ChildProps
- comment()
- Comment
- CommentProps
- Container
- ContainerProps
- CssSyntaxError
- decl()
- Declaration
- DeclarationProps
- document()
- Document
- DocumentProps
- FilePosition
- fromJSON
- Helpers
- Input
- JSONHydrator
- LazyResult
- Message
- NewChild
- Node
- NodeErrorOptions
- NodeProps
- OldPlugin
- parse
- Parser
- Plugin
- PluginCreator
- Position
- postcss()
- Postcss
- ProcessOptions
- Processor
- Result
- root()
- Root
- RootProps
- rule()
- Rule
- RuleProps
- Source
- SourceMap
- SourceMapOptions
- Stringifier
- stringify
- Syntax
- TransformCallback
- Transformer
- Warning
- WarningOptions
Variables
variable fromJSON
let fromJSON: JSONHydrator;
Rehydrate a JSON AST (from
Node#toJSON
) back into the AST classes.const json = root.toJSON()// save to file, send by network, etcconst root2 = postcss.fromJSON(json)
variable parse
let parse: Parser<Root>;
Parses source css and returns a new
Root
orDocument
node, which contains the source CSS nodes.// Simple CSS concatenation with source map supportconst root1 = postcss.parse(css1, { from: file1 })const root2 = postcss.parse(css2, { from: file2 })root1.append(root2).toResult().css
variable stringify
let stringify: Stringifier;
Default function to convert a node tree into a CSS string.
Functions
function atRule
atRule: (defaults?: AtRuleProps) => AtRule;
Creates a new
AtRule
node.Parameter defaults
Properties for the new node. New at-rule node.
function comment
comment: (defaults?: CommentProps) => Comment;
Creates a new
Comment
node.Parameter defaults
Properties for the new node. New comment node
function decl
decl: (defaults?: DeclarationProps) => Declaration;
Creates a new
Declaration
node.Parameter defaults
Properties for the new node. New declaration node.
function document
document: (defaults?: DocumentProps) => Document;
Creates a new
Document
node.Parameter defaults
Properties for the new node. New document node.
function postcss
postcss: typeof postcss;
Create a new
Processor
instance that will applyplugins
as CSS processors.let postcss = require('postcss')postcss(plugins).process(css, { from, to }).then(result => {console.log(result.css)})Parameter plugins
PostCSS plugins. Processor to process multiple CSS.
function postcss
postcss: typeof postcss;
Create a new
Processor
instance that will applyplugins
as CSS processors.let postcss = require('postcss')postcss(plugins).process(css, { from, to }).then(result => {console.log(result.css)})Parameter plugins
PostCSS plugins. Processor to process multiple CSS.
function root
root: (defaults?: RootProps) => Root;
Creates a new
Root
node.Parameter defaults
Properties for the new node. New root node.
function rule
rule: (defaults?: RuleProps) => Rule;
Creates a new
Rule
node.Parameter default
Properties for the new node. New rule node.
Classes
class AtRule
class AtRule_ extends Container {}
Represents an at-rule.
Once (root, { AtRule }) {let media = new AtRule({ name: 'media', params: 'print' })media.append(…)root.append(media)}If it’s followed in the CSS by a
{}
block, this node will have a nodes property representing its children.const root = postcss.parse('@charset "UTF-8"; @media print {}')const charset = root.firstcharset.type //=> 'atrule'charset.nodes //=> undefinedconst media = root.lastmedia.nodes //=> []
constructor
constructor(defaults?: AtRule.AtRuleProps);
property name
name: string;
The at-rule’s name immediately follows the
@
.const root = postcss.parse('@media print {}')const media = root.firstmedia.name //=> 'media'
property nodes
nodes: Node.ChildNode[];
An array containing the layer’s children.
const root = postcss.parse('@layer example { a { color: black } }')const layer = root.firstlayer.nodes.length //=> 1layer.nodes[0].selector //=> 'a'Can be
undefinded
if the at-rule has no body.const root = postcss.parse('@layer a, b, c;')const layer = root.firstlayer.nodes //=> undefined
property params
params: string;
The at-rule’s parameters, the values that follow the at-rule’s name but precede any
{}
block.const root = postcss.parse('@media print, screen {}')const media = root.firstmedia.params //=> 'print, screen'
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property raws
raws: AtRule.AtRuleRaws;
property type
type: string;
method assign
assign: (overrides: AtRule.AtRuleProps | object) => this;
method clone
clone: (overrides?: Partial<AtRule.AtRuleProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<AtRule.AtRuleProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<AtRule.AtRuleProps>) => this;
class Comment
class Comment_ extends Node {}
It represents a class that handles [CSS comments](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments)
Once (root, { Comment }) {const note = new Comment({ text: 'Note: …' })root.append(note)}Remember that CSS comments inside selectors, at-rule parameters, or declaration values will be stored in the
raws
properties explained above.
constructor
constructor(defaults?: Comment.CommentProps);
property parent
parent: Container<Node.ChildNode>;
property raws
raws: Comment.CommentRaws;
property text
text: string;
The comment's text.
property type
type: string;
method assign
assign: (overrides: Comment.CommentProps | object) => this;
method clone
clone: (overrides?: Partial<Comment.CommentProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Comment.CommentProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Comment.CommentProps>) => this;
class Container
abstract class Container_<Child extends Node = ChildNode> extends Node {}
The
Root
,AtRule
, andRule
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.
property first
readonly first: Node;
The container’s first child.
rule.first === rules.nodes[0]
property last
readonly last: Node;
The container’s last child.
rule.last === rule.nodes[rule.nodes.length - 1]
property nodes
nodes: Child[];
An array containing the container’s children.
const root = postcss.parse('a { color: black }')root.nodes.length //=> 1root.nodes[0].selector //=> 'a'root.nodes[0].nodes[0].prop //=> 'color'
method append
append: (...nodes: Container.NewChild[]) => this;
Inserts new nodes to the end of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })const decl2 = new Declaration({ prop: 'background-color', value: 'white' })rule.append(decl1, decl2)root.append({ name: 'charset', params: '"UTF-8"' }) // at-ruleroot.append({ selector: 'a' }) // rulerule.append({ prop: 'color', value: 'black' }) // declarationrule.append({ text: 'Comment' }) // commentroot.append('a {}')root.first.append('color: black; z-index: 1')Parameter nodes
New nodes. This node for methods chain.
method assign
assign: (overrides: Container.ContainerProps | object) => this;
method clone
clone: (overrides?: Partial<Container.ContainerProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Container.ContainerProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Container.ContainerProps>) => this;
method each
each: ( callback: (node: Child, index: number) => false | void) => false | undefined;
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 orArray#forEach
this iterator is safe if you are mutating the array of child nodes during iteration. PostCSS will adjust the current index to match the mutations.const root = postcss.parse('a { color: black; z-index: 1 }')const rule = root.firstfor (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})Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method every
every: ( condition: (node: Child, index: number, nodes: Child[]) => boolean) => boolean;
Returns
true
if callback returnstrue
for all of the container’s children.const noPrefixes = rule.every(i => i.prop[0] !== '-')Parameter condition
Iterator returns true or false. Is every child pass condition.
method index
index: (child: Child | number) => number;
Returns a
child
’s index within theContainer#nodes
array.rule.index( rule.nodes[2] ) //=> 2Parameter child
Child of the current container. Child index.
method insertAfter
insertAfter: (oldNode: Child | number, newNode: Container.NewChild) => this;
Insert new node after old node within the container.
Parameter oldNode
Child or child’s index.
Parameter newNode
New node. This node for methods chain.
method insertBefore
insertBefore: (oldNode: Child | number, newNode: Container.NewChild) => this;
Insert new node before old node within the container.
rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))Parameter oldNode
Child or child’s index.
Parameter newNode
New node. This node for methods chain.
method normalize
protected normalize: ( nodes: Container.NewChild, sample: Node | undefined, type?: 'prepend' | false) => Child[];
An internal method that converts a NewChild into a list of actual child nodes that can then be added to this container.
This ensures that the nodes' parent is set to this container, that they use the correct prototype chain, and that they're marked as dirty.
Parameter mnodes
The new node or nodes to add.
Parameter sample
A node from whose raws the new node's
before
raw should be taken.Parameter type
This should be set to
'prepend'
if the new nodes will be inserted at the beginning of the container.
method prepend
prepend: (...nodes: Container.NewChild[]) => this;
Inserts new nodes to the start of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })const decl2 = new Declaration({ prop: 'background-color', value: 'white' })rule.prepend(decl1, decl2)root.append({ name: 'charset', params: '"UTF-8"' }) // at-ruleroot.append({ selector: 'a' }) // rulerule.append({ prop: 'color', value: 'black' }) // declarationrule.append({ text: 'Comment' }) // commentroot.append('a {}')root.first.append('color: black; z-index: 1')Parameter nodes
New nodes. This node for methods chain.
method push
push: (child: Child) => this;
Add child to the end of the node.
rule.push(new Declaration({ prop: 'color', value: 'black' }))Parameter child
New node. This node for methods chain.
method removeAll
removeAll: () => this;
Removes all children from the container and cleans their parent properties.
rule.removeAll()rule.nodes.length //=> 0This node for methods chain.
method removeChild
removeChild: (child: Child | number) => this;
Removes node from the container and cleans the parent properties from the node and its children.
rule.nodes.length //=> 5rule.removeChild(decl)rule.nodes.length //=> 4decl.parent //=> undefinedParameter child
Child or child’s index. This node for methods chain.
method replaceValues
replaceValues: { ( pattern: RegExp | string, replaced: string | ((substring: string, ...args: any[]) => string) ): this; ( pattern: string | RegExp, options: Container.ValueOptions, replaced: string | ((substring: string, ...args: any[]) => string) ): this;};
Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.
This method is useful if you are using a custom unit or function and need to iterate through all values.
root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {return 15 * parseInt(string) + 'px'})Parameter pattern
Replace pattern.
Parameter options
Options to speed up the search.
Parameter replaced
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
. This node for methods chain.
method some
some: ( condition: (node: Child, index: number, nodes: Child[]) => boolean) => boolean;
Returns
true
if callback returnstrue
for (at least) one of the container’s children.const hasPrefix = rule.some(i => i.prop[0] === '-')Parameter condition
Iterator returns true or false. Is some child pass condition.
method walk
walk: ( callback: (node: ChildNode, index: number) => false | void) => false | undefined;
Traverses the container’s descendant nodes, calling callback for each node.
Like container.each(), this method is safe to use if you are mutating arrays during iteration.
If you only need to iterate through the container’s immediate children, use
Container#each
.root.walk(node => {// Traverses all descendant nodes.})Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkAtRules
walkAtRules: { ( nameFilter: RegExp | string, callback: (atRule: AtRule, index: number) => false | void ): false | undefined; (callback: (atRule: AtRule, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each at-rule node.
If you pass a filter, iteration will only happen over at-rules that have matching names.
Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.root.walkAtRules(rule => {if (isOld(rule.name)) rule.remove()})let first = falseroot.walkAtRules('charset', rule => {if (!first) {first = true} else {rule.remove()}})Parameter name
String or regular expression to filter at-rules by name.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkComments
walkComments: { (callback: (comment: Comment, indexed: number) => false | void): | false | undefined; (callback: (comment: Comment, indexed: number) => false | void): false;};
method walkDecls
walkDecls: { ( propFilter: RegExp | string, callback: (decl: Declaration, index: number) => false | void ): false | undefined; (callback: (decl: Declaration, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each declaration node.
If you pass a filter, iteration will only happen over declarations with matching properties.
root.walkDecls(decl => {checkPropertySupport(decl.prop)})root.walkDecls('border-radius', decl => {decl.remove()})root.walkDecls(/^background/, decl => {decl.value = takeFirstColorFromGradient(decl.value)})Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.Parameter prop
String or regular expression to filter declarations by property name.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkRules
walkRules: { ( selectorFilter: RegExp | string, callback: (rule: Rule, index: number) => false | void ): false | undefined; (callback: (rule: Rule, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each rule node.
If you pass a filter, iteration will only happen over rules with matching selectors.
Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.const selectors = []root.walkRules(rule => {selectors.push(rule.selector)})console.log(`Your CSS uses ${ selectors.length } selectors`)Parameter selector
String or regular expression to filter rules by selector.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
class CssSyntaxError
class CssSyntaxError_ extends Error {}
The CSS parser throws this error for broken CSS.
Custom parsers can throw this error for broken custom syntax using the
Node#error
method.PostCSS will use the input source map to detect the original error location. If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS, PostCSS will show the original position in the Sass file.
If you need the position in the PostCSS input (e.g., to debug the previous compiler), use
error.input.file
.// Raising error from pluginthrow node.error('Unknown variable', { plugin: 'postcss-vars' })// Catching and checking syntax errortry {postcss.parse('a{')} catch (error) {if (error.name === 'CssSyntaxError') {error //=> CssSyntaxError}}
constructor
constructor( message: string, lineOrStartPos?: number | CssSyntaxError.RangePosition, columnOrEndPos?: number | CssSyntaxError.RangePosition, source?: string, file?: string, plugin?: string);
Instantiates a CSS syntax error. Can be instantiated for a single position or for a range.
Parameter message
Error message.
Parameter lineOrStartPos
If for a single position, the line number, or if for a range, the inclusive start position of the error.
Parameter columnOrEndPos
If for a single position, the column number, or if for a range, the exclusive end position of the error.
Parameter source
Source code of the broken file.
Parameter file
Absolute path to the broken file.
Parameter plugin
PostCSS plugin name, if error came from plugin.
property column
column?: number;
Source column of the error.
error.column //=> 1error.input.column //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.column
.
property endColumn
endColumn?: number;
Source column of the error's end, exclusive. Provided if the error pertains to a range.
error.endColumn //=> 1error.input.endColumn //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.endColumn
.
property endLine
endLine?: number;
Source line of the error's end, exclusive. Provided if the error pertains to a range.
error.endLine //=> 3error.input.endLine //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.endLine
.
property file
file?: string;
Absolute path to the broken file.
error.file //=> 'a.sass'error.input.file //=> 'a.css'PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.file
.
property input
input?: FilePosition;
Input object with PostCSS internal information about input file. If input has source map from previous tool, PostCSS will use origin (for example, Sass) source. You can use this object to get PostCSS input source.
error.input.file //=> 'a.css'error.file //=> 'a.sass'
property line
line?: number;
Source line of the error.
error.line //=> 2error.input.line //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.line
.
property message
message: string;
Full error text in the GNU error format with plugin, file, line and column.
error.message //=> 'a.css:1:1: Unclosed block'
property name
name: string;
Always equal to
'CssSyntaxError'
. You should always check error type byerror.name === 'CssSyntaxError'
instead oferror instanceof CssSyntaxError
, because npm could have several PostCSS versions.if (error.name === 'CssSyntaxError') {error //=> CssSyntaxError}
property plugin
plugin?: string;
Plugin name, if error came from plugin.
error.plugin //=> 'postcss-vars'
property reason
reason: string;
Error message.
error.message //=> 'Unclosed block'
property source
source?: string;
Source code of the broken file.
error.source //=> 'a { b {} }'error.input.source //=> 'a b { }'
property stack
stack: string;
method showSourceCode
showSourceCode: (color?: boolean) => string;
Returns a few lines of CSS source that caused the error.
If the CSS has an input source map without
sourceContent
, this method will return an empty string.error.showSourceCode() //=> " 4 | }// 5 | a {// > 6 | bad// | ^// 7 | }// 8 | b {"Parameter color
Whether arrow will be colored red by terminal color codes. By default, PostCSS will detect color support by
process.stdout.isTTY
andprocess.env.NODE_DISABLE_COLORS
. Few lines of CSS source that caused the error.
method toString
toString: () => string;
Returns error position, message and source code of the broken part.
error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block// > 1 | a {// | ^"Error position, message and source code.
class Declaration
class Declaration_ extends Node {}
It represents a class that handles [CSS declarations](https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_declarations)
Once (root, { Declaration }) {const color = new Declaration({ prop: 'color', value: 'black' })root.append(color)}const root = postcss.parse('a { color: black }')const decl = root.first?.firstdecl.type //=> 'decl'decl.toString() //=> ' color: black'
constructor
constructor(defaults?: Declaration.DeclarationProps);
property important
important: boolean;
It represents a specificity of the declaration.
If true, the CSS declaration will have an [important](https://developer.mozilla.org/en-US/docs/Web/CSS/important) specifier.
const root = postcss.parse('a { color: black !important; color: red }')root.first.first.important //=> trueroot.first.last.important //=> undefined
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property prop
prop: string;
The property name for a CSS declaration.
const root = postcss.parse('a { color: black }')const decl = root.first.firstdecl.prop //=> 'color'
property raws
raws: Declaration.DeclarationRaws;
property type
type: string;
property value
value: string;
The property value for a CSS declaration.
Any CSS comments inside the value string will be filtered out. CSS comments present in the source value will be available in the
raws
property.Assigning new
value
would ignore the comments inraws
property while compiling node to string.const root = postcss.parse('a { color: black }')const decl = root.first.firstdecl.value //=> 'black'
property variable
readonly variable: boolean;
It represents a getter that returns
true
if a declaration starts with--
or$
, which are used to declare variables in CSS and SASS/SCSS.const root = postcss.parse(':root { --one: 1 }')const one = root.first.firstone.variable //=> trueconst root = postcss.parse('$one: 1')const one = root.firstone.variable //=> true
method assign
assign: (overrides: Declaration.DeclarationProps | object) => this;
method clone
clone: (overrides?: Partial<Declaration.DeclarationProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Declaration.DeclarationProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Declaration.DeclarationProps>) => this;
class Document
class Document_ extends Container<Root> {}
Represents a file and contains all its parsed nodes.
**Experimental:** some aspects of this node could change within minor or patch version releases.
const document = htmlParser('<html><style>a{color:black}</style><style>b{z-index:2}</style>')document.type //=> 'document'document.nodes.length //=> 2
constructor
constructor(defaults?: Document.DocumentProps);
property nodes
nodes: Root[];
property parent
parent: undefined;
property type
type: string;
method assign
assign: (overrides: Document.DocumentProps | object) => this;
method clone
clone: (overrides?: Partial<Document.DocumentProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Document.DocumentProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Document.DocumentProps>) => this;
method toResult
toResult: (options?: ProcessOptions) => Result;
Returns a
Result
instance representing the document’s CSS roots.const root1 = postcss.parse(css1, { from: 'a.css' })const root2 = postcss.parse(css2, { from: 'b.css' })const document = postcss.document()document.append(root1)document.append(root2)const result = document.toResult({ to: 'all.css', map: true })Parameter opts
Options. Result with current document’s CSS.
class Input
class Input_ {}
Represents the source CSS.
const root = postcss.parse(css, { from: file })const input = root.source.input
constructor
constructor(css: string, opts?: ProcessOptions<Document_ | Root_>);
Parameter css
Input CSS source.
Parameter opts
Process options.
property css
css: string;
Input CSS source.
const input = postcss.parse('a{}', { from: file }).inputinput.css //=> "a{}"
property file
file?: string;
The absolute path to the CSS source file defined with the
from
option.const root = postcss.parse(css, { from: 'a.css' })root.source.input.file //=> '/home/ai/a.css'
property from
readonly from: string;
The CSS source identifier. Contains
Input#file
if the user set thefrom
option, orInput#id
if they did not.const root = postcss.parse(css, { from: 'a.css' })root.source.input.from //=> "/home/ai/a.css"const root = postcss.parse(css)root.source.input.from //=> "<input css 1>"
property hasBOM
hasBOM: boolean;
The flag to indicate whether or not the source code has Unicode BOM.
property id
id?: string;
The unique ID of the CSS source. It will be created if
from
option is not provided (because PostCSS does not know the file path).const root = postcss.parse(css)root.source.input.file //=> undefinedroot.source.input.id //=> "<input css 8LZeVF>"
property map
map: PreviousMap;
The input source map passed from a compilation step before PostCSS (for example, from Sass compiler).
root.source.input.map.consumer().sources //=> ['a.sass']
method error
error: { ( message: string, start: { column: number; line: number } | { offset: number }, end: { column: number; line: number } | { offset: number }, opts?: { plugin?: CssSyntaxError['plugin'] } ): CssSyntaxError; ( message: string, line: number, column: number, opts?: { plugin?: string } ): CssSyntaxError; ( message: string, offset: number, opts?: { plugin?: string } ): CssSyntaxError;};
Returns
CssSyntaxError
with information about the error and its position.
method fromOffset
fromOffset: (offset: number) => { col: number; line: number } | null;
Converts source offset to line and column.
Parameter offset
Source offset.
method origin
origin: ( line: number, column: number, endLine?: number, endColumn?: number) => false | Input.FilePosition;
Reads the input source map and returns a symbol position in the input source (e.g., in a Sass file that was compiled to CSS before being passed to PostCSS). Optionally takes an end position, exclusive.
root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }root.source.input.origin(1, 1, 1, 4)//=> { file: 'a.css', line: 3, column: 1, endLine: 3, endColumn: 4 }Parameter line
Line for inclusive start position in input CSS.
Parameter column
Column for inclusive start position in input CSS.
Parameter endLine
Line for exclusive end position in input CSS.
Parameter endColumn
Column for exclusive end position in input CSS.
Position in input source.
method toJSON
toJSON: () => object;
Converts this to a JSON-friendly object representation.
class LazyResult
class LazyResult_<RootNode = Document | Root> implements PromiseLike<Result<RootNode>> {}
A Promise proxy for the result of PostCSS transformations.
A
LazyResult
instance is returned byProcessor#process
.const lazy = postcss([autoprefixer]).process(css)
constructor
constructor(processor: Processor, css: string, opts: ResultOptions);
Parameter processor
Processor used for this transformation.
Parameter css
CSS to parse and transform.
Parameter opts
Options from the
Processor#process
orRoot#toResult
.
property [Symbol.toStringTag]
readonly [Symbol.toStringTag]: string;
Returns the default string description of an object. Required to implement the Promise interface.
property catch
catch: <TResult = never>( onrejected?: (reason: any) => TResult | PromiseLike<TResult>) => Promise<Result<RootNode> | TResult>;
Processes input CSS through synchronous and asynchronous plugins and calls onRejected for each error thrown in any plugin.
It implements standard Promise API.
postcss([autoprefixer]).process(css).then(result => {console.log(result.css)}).catch(error => {console.error(error)})
property content
readonly content: string;
An alias for the
css
property. Use it with syntaxes that generate non-CSS output.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property css
readonly css: string;
Processes input CSS through synchronous plugins, converts
Root
to a CSS string and returnsResult#css
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property finally
finally: (onfinally?: () => void) => Promise<Result<RootNode>>;
Processes input CSS through synchronous and asynchronous plugins and calls onFinally on any error or when all plugins will finish work.
It implements standard Promise API.
postcss([autoprefixer]).process(css).finally(() => {console.log('processing ended')})
property map
readonly map: any;
Processes input CSS through synchronous plugins and returns
Result#map
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property messages
readonly messages: Message[];
Processes input CSS through synchronous plugins and returns
Result#messages
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property opts
readonly opts: ResultOptions;
Options from the
Processor#process
call.
property processor
readonly processor: Processor;
Returns a
Processor
instance, which will be used for CSS transformations.
property root
readonly root: {};
Processes input CSS through synchronous plugins and returns
Result#root
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property then
then: <TResult1 = Result<RootNode>, TResult2 = never>( onfulfilled?: (value: Result<RootNode>) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<TResult1 | TResult2>;
Processes input CSS through synchronous and asynchronous plugins and calls
onFulfilled
with a Result instance. If a plugin throws an error, theonRejected
callback will be executed.It implements standard Promise API.
postcss([autoprefixer]).process(css, { from: cssPath }).then(result => {console.log(result.css)})
method async
async: () => Promise<Result<RootNode>>;
Run plugin in async way and return
Result
.Result with output content.
method sync
sync: () => Result<RootNode>;
Run plugin in sync way and return
Result
.Result with output content.
method toString
toString: () => string;
Alias for the
LazyResult#css
property.lazy + '' === lazy.cssOutput CSS.
method warnings
warnings: () => Warning[];
Processes input CSS through synchronous plugins and calls
Result#warnings
.Warnings from plugins.
class Node
class Node extends Node_ {}
class Processor
class Processor_ {}
Contains plugins to process CSS. Create one
Processor
instance, initialize its plugins, and then use that instance on numerous CSS files.const processor = postcss([autoprefixer, postcssNested])processor.process(css1).then(result => console.log(result.css))processor.process(css2).then(result => console.log(result.css))
constructor
constructor(plugins?: readonly AcceptedPlugin[]);
Parameter plugins
PostCSS plugins
property plugins
plugins: (Plugin | TransformCallback | Transformer)[];
Plugins added to this processor.
const processor = postcss([autoprefixer, postcssNested])processor.plugins.length //=> 2
property version
version: string;
Current PostCSS version.
if (result.processor.version.split('.')[0] !== '6') {throw new Error('This plugin works only with PostCSS 6')}
method process
process: { (css: { toString(): string } | LazyResult | Result | Root | string): | LazyResult | NoWorkResult; <RootNode extends Document | Root = Root>( css: | string | Root | Result<Document | Root> | LazyResult<Document | Root> | { toString(): string }, options: ProcessOptions<RootNode> ): LazyResult<RootNode>;};
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 theLazyResult
methods.processor.process(css, { from: 'a.css', to: 'a.out.css' }).then(result => {console.log(result.css)})Parameter css
String with input CSS or any object with a
toString()
method, like a Buffer. Optionally, send aResult
instance and the processor will take theRoot
from it.Parameter opts
Options. Promise proxy.
method use
use: (plugin: AcceptedPlugin) => this;
Adds a plugin to be used as a CSS processor.
PostCSS plugin can be in 4 formats: * A plugin in
Plugin
format. * A plugin creator function withpluginCreator.postcss = true
. PostCSS will call this function without argument to get plugin. * A function. PostCSS will pass the function a Root as the first argument and currentResult
instance as the second. * AnotherProcessor
instance. PostCSS will copy plugins from that instance into this one.Plugins can also be added by passing them as arguments when creating a
postcss
instance (see [postcss(plugins)
]).Asynchronous plugins should return a
Promise
instance.const processor = postcss().use(autoprefixer).use(postcssNested)Parameter plugin
PostCSS plugin or
Processor
with plugins. Current processor to make methods chain.
class Result
class Result_<RootNode = Document | Root> {}
Provides the result of the PostCSS transformations.
A Result instance is returned by
LazyResult#then
orRoot#toResult
methods.postcss([autoprefixer]).process(css).then(result => {console.log(result.css)})const result2 = postcss.parse(css).toResult()
constructor
constructor(processor: Processor, root: {}, opts: Result.ResultOptions);
Parameter processor
Processor used for this transformation.
Parameter root
Root node after all transformations.
Parameter opts
Options from the
Processor#process
orRoot#toResult
.
property content
readonly content: string;
An alias for the
Result#css
property. Use it with syntaxes that generate non-CSS output.result.css === result.content
property css
css: string;
A CSS string representing of
Result#root
.postcss.parse('a{}').toResult().css //=> "a{}"
property lastPlugin
lastPlugin: Plugin | TransformCallback;
Last runned PostCSS plugin.
property map
map: any;
An instance of
SourceMapGenerator
class from thesource-map
library, representing changes to theResult#root
instance.result.map.toJSON() //=> { version: 3, file: 'a.css', … }if (result.map) {fs.writeFileSync(result.opts.to + '.map', result.map.toString())}
property messages
messages: Result.Message[];
Contains messages from plugins (e.g., warnings or custom messages). Each message should have type and plugin properties.
AtRule: {import: (atRule, { result }) {const importedFile = parseImport(atRule)result.messages.push({type: 'dependency',plugin: 'postcss-import',file: importedFile,parent: result.opts.from})}}
property opts
opts: Result.ResultOptions;
Options from the
Processor#process
orRoot#toResult
call that produced this Result instance.]root.toResult(opts).opts === opts
property processor
processor: Processor;
The Processor instance used for this transformation.
for (const plugin of result.processor.plugins) {if (plugin.postcssPlugin === 'postcss-bad') {throw 'postcss-good is incompatible with postcss-bad'}})
property root
root: {};
Root node after all transformations.
root.toResult().root === root
method toString
toString: () => string;
Returns for
Result#css
content.result + '' === result.cssString representing of
Result#root
.
method warn
warn: (message: string, options?: WarningOptions) => Warning;
Creates an instance of
Warning
and adds it toResult#messages
.if (decl.important) {result.warn('Avoid !important', { node: decl, word: '!important' })}Parameter text
Warning message.
Parameter opts
Warning options. Created warning.
method warnings
warnings: () => Warning[];
Returns warnings from plugins. Filters
Warning
instances fromResult#messages
.result.warnings().forEach(warn => {console.warn(warn.toString())})Warnings from plugins.
class Root
class Root_ extends Container {}
Represents a CSS file and contains all its parsed nodes.
const root = postcss.parse('a{color:black} b{z-index:2}')root.type //=> 'root'root.nodes.length //=> 2
constructor
constructor(defaults?: Root.RootProps);
property nodes
nodes: Node.ChildNode[];
property parent
parent: Document;
property raws
raws: Root.RootRaws;
property type
type: string;
method assign
assign: (overrides: object | Root.RootProps) => this;
method clone
clone: (overrides?: Partial<Root.RootProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Root.RootProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Root.RootProps>) => this;
method toResult
toResult: (options?: ProcessOptions) => Result;
Returns a
Result
instance representing the root’s CSS.const root1 = postcss.parse(css1, { from: 'a.css' })const root2 = postcss.parse(css2, { from: 'b.css' })root1.append(root2)const result = root1.toResult({ to: 'all.css', map: true })Parameter options
Options. Result with current root’s CSS.
class Rule
class Rule_ extends Container {}
Represents a CSS rule: a selector followed by a declaration block.
Once (root, { Rule }) {let a = new Rule({ selector: 'a' })a.append(…)root.append(a)}const root = postcss.parse('a{}')const rule = root.firstrule.type //=> 'rule'rule.toString() //=> 'a{}'
constructor
constructor(defaults?: Rule.RuleProps);
property nodes
nodes: Node.ChildNode[];
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property raws
raws: Rule.RuleRaws;
property selector
selector: string;
The rule’s full selector represented as a string.
const root = postcss.parse('a, b { }')const rule = root.firstrule.selector //=> 'a, b'
property selectors
selectors: string[];
An array containing the rule’s individual selectors. Groups of selectors are split at commas.
const root = postcss.parse('a, b { }')const rule = root.firstrule.selector //=> 'a, b'rule.selectors //=> ['a', 'b']rule.selectors = ['a', 'strong']rule.selector //=> 'a, strong'
property type
type: string;
method assign
assign: (overrides: object | Rule.RuleProps) => this;
method clone
clone: (overrides?: Partial<Rule.RuleProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Rule.RuleProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Rule.RuleProps>) => this;
class Warning
class Warning_ {}
Represents a plugin’s warning. It can be created using
Node#warn
.if (decl.important) {decl.warn(result, 'Avoid !important', { word: '!important' })}
constructor
constructor(text: string, opts?: Warning.WarningOptions);
Parameter text
Warning message.
Parameter opts
Warning options.
property column
column: number;
Column for inclusive start position in the input file with this warning’s source.
warning.column //=> 6
property endColumn
endColumn?: number;
Column for exclusive end position in the input file with this warning’s source.
warning.endColumn //=> 4
property endLine
endLine?: number;
Line for exclusive end position in the input file with this warning’s source.
warning.endLine //=> 6
property line
line: number;
Line for inclusive start position in the input file with this warning’s source.
warning.line //=> 5
property node
node: Node;
Contains the CSS node that caused the warning.
warning.node.toString() //=> 'color: white !important'
property plugin
plugin: string;
The name of the plugin that created this warning. When you call
Node#warn
it will fill this property automatically.warning.plugin //=> 'postcss-important'
property text
text: string;
The warning message.
warning.text //=> 'Try to avoid !important'
property type
type: string;
Type to filter warnings from
Result#messages
. Always equal to"warning"
.
method toString
toString: () => string;
Returns a warning position and message.
warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'Warning position and message.
Interfaces
interface AtRuleProps
interface AtRuleProps extends ContainerProps {}
interface Builder
interface Builder {}
call signature
(part: string, node?: AnyNode, type?: 'end' | 'start'): void;
interface CommentProps
interface CommentProps extends NodeProps {}
interface ContainerProps
interface ContainerProps extends NodeProps {}
property nodes
nodes?: readonly (ChildProps | Node)[];
interface DeclarationProps
interface DeclarationProps {}
property important
important?: boolean;
Whether the declaration has an
!important
annotation.
property prop
prop: string;
Name of the declaration.
property raws
raws?: DeclarationRaws;
Information used to generate byte-to-byte equal node string as it was in the origin input.
property value
value: string;
Value of the declaration.
interface DocumentProps
interface DocumentProps extends ContainerProps {}
interface FilePosition
interface FilePosition {}
property column
column: number;
Column of inclusive start position in source file.
property endColumn
endColumn?: number;
Column of exclusive end position in source file.
property endLine
endLine?: number;
Line of exclusive end position in source file.
property file
file?: string;
Absolute path to the source file.
property line
line: number;
Line of inclusive start position in source file.
property source
source?: string;
Source code.
property url
url: string;
URL for the source file.
interface JSONHydrator
interface JSONHydrator {}
call signature
(data: object): Node;
call signature
(data: object[]): Node[];
interface Message
interface Message {}
property plugin
plugin?: string;
Source PostCSS plugin name.
property type
type: string;
Message type.
index signature
[others: string]: any;
interface NodeErrorOptions
interface NodeErrorOptions {}
property endIndex
endIndex?: number;
An ending index inside a node's string that should be highlighted as source of error.
property index
index?: number;
An index inside a node's string that should be highlighted as source of error.
property plugin
plugin?: string;
Plugin name that created this error. PostCSS will set it automatically.
property word
word?: string;
A word inside a node's string, that should be highlighted as source of error.
interface NodeProps
interface NodeProps {}
Interface represents an interface for an object received as parameter by Node class constructor.
property source
source?: Source;
interface OldPlugin
interface OldPlugin<T> extends Transformer {}
property postcss
postcss: Transformer;
call signature
(opts?: T): Transformer;
interface Parser
interface Parser<RootNode = Document | Root> {}
call signature
( css: { toString(): string } | string, opts?: Pick<ProcessOptions, 'from' | 'map'>): RootNode;
interface Plugin
interface Plugin extends Processors {}
property postcssPlugin
postcssPlugin: string;
property prepare
prepare?: (result: Result) => Processors;
interface PluginCreator
interface PluginCreator<PluginOptions> {}
property postcss
postcss: true;
call signature
(opts?: PluginOptions): Plugin | Processor;
interface Position
interface Position {}
interface ProcessOptions
interface ProcessOptions<RootNode = Document | Root> {}
property from
from?: string | undefined;
The path of the CSS source file. You should always set
from
, because it is used in source map generation and syntax error messages.
property map
map?: boolean | SourceMapOptions;
Source map options
property parser
parser?: Parser<RootNode> | Syntax<RootNode>;
Function to generate AST by string.
property stringifier
stringifier?: Stringifier | Syntax<RootNode>;
Class to generate string by AST.
property syntax
syntax?: Syntax<RootNode>;
Object with parse and stringify.
property to
to?: string;
The path where you'll put the output CSS file. You should always set
to
to generate correct source maps.
interface RootProps
interface RootProps extends ContainerProps {}
property raws
raws?: RootRaws;
Information used to generate byte-to-byte equal node string as it was in the origin input.
interface Source
interface Source {}
Source represents an interface for the Node.source property.
interface SourceMapOptions
interface SourceMapOptions {}
property absolute
absolute?: boolean;
Use absolute path in generated source map.
property annotation
annotation?: ((file: string, root: Root) => string) | boolean | string;
Indicates that PostCSS should add annotation comments to the CSS. By default, PostCSS will always add a comment with a path to the source map. PostCSS will not add annotations to CSS files that do not contain any comments.
By default, PostCSS presumes that you want to save the source map as
opts.to + '.map'
and will use this path in the annotation comment. A different path can be set by providing a string value for annotation.If you have set
inline: true
, annotation cannot be disabled.
property from
from?: string;
Override
from
in map’s sources.
property inline
inline?: boolean;
Indicates that the source map should be embedded in the output CSS as a Base64-encoded comment. By default, it is
true
. But if all previous maps are external, not inline, PostCSS will not embed the map even if you do not set this option.If you have an inline source map, the result.map property will be empty, as the source map will be contained within the text of
result.css
.
property prev
prev?: ((file: string) => string) | boolean | object | string;
Source map content from a previous processing step (e.g., Sass).
PostCSS will try to read the previous source map automatically (based on comments within the source CSS), but you can use this option to identify it manually.
If desired, you can omit the previous map with prev:
false
.
property sourcesContent
sourcesContent?: boolean;
Indicates that PostCSS should set the origin content (e.g., Sass source) of the source map. By default, it is true. But if all previous maps do not contain sources content, PostCSS will also leave it out even if you do not set this option.
interface Stringifier
interface Stringifier {}
call signature
(node: AnyNode, builder: Builder): void;
interface Syntax
interface Syntax<RootNode = Document | Root> {}
interface TransformCallback
interface TransformCallback {}
call signature
(root: Root, result: Result): Promise<void> | void;
interface Transformer
interface Transformer extends TransformCallback {}
property postcssPlugin
postcssPlugin: string;
property postcssVersion
postcssVersion: string;
interface WarningOptions
interface WarningOptions {}
property end
end?: RangePosition;
End position, exclusive, in CSS node string that caused the warning.
property endIndex
endIndex?: number;
End index, exclusive, in CSS node string that caused the warning.
property index
index?: number;
Start index, inclusive, in CSS node string that caused the warning.
property node
node?: Node;
CSS node that caused the warning.
property plugin
plugin?: string;
Name of the plugin that created this warning.
Result#warn
fills this property automatically.
property start
start?: RangePosition;
Start position, inclusive, in CSS node string that caused the warning.
property word
word?: string;
Word in CSS source that caused the warning.
Type Aliases
type AcceptedPlugin
type AcceptedPlugin = | { postcss: Processor | TransformCallback; } | OldPlugin<any> | Plugin | PluginCreator<any> | Processor | TransformCallback;
type AnyNode
type AnyNode = AtRule.default | Comment | Declaration | Document | Root | Rule;
type ChildNode
type ChildNode = AtRule.default | Comment | Declaration | Rule;
type ChildProps
type ChildProps = AtRuleProps | CommentProps | DeclarationProps | RuleProps;
type Helpers
type Helpers = { postcss: Postcss; result: Result } & Postcss;
type NewChild
type NewChild = | ChildProps | Node | readonly ChildProps[] | readonly Node[] | readonly string[] | string | undefined;
All types that can be passed into container methods to create or add a new child node.
type Postcss
type Postcss = typeof postcss;
type RuleProps
type RuleProps = { /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ raws?: RuleRaws;} & ( | { /** Selector or selectors of the rule. */ selector: string; selectors?: never; } | { selector?: never; /** Selectors of the rule represented as an array of strings. */ selectors: readonly string[]; }) & ContainerProps;
type SourceMap
type SourceMap = { toJSON(): RawSourceMap;} & SourceMapGenerator;
Namespaces
namespace postcss
namespace postcss {}
variable fromJSON
let fromJSON: JSONHydrator;
Rehydrate a JSON AST (from
Node#toJSON
) back into the AST classes.const json = root.toJSON()// save to file, send by network, etcconst root2 = postcss.fromJSON(json)
variable parse
let parse: Parser<Root>;
Parses source css and returns a new
Root
orDocument
node, which contains the source CSS nodes.// Simple CSS concatenation with source map supportconst root1 = postcss.parse(css1, { from: file1 })const root2 = postcss.parse(css2, { from: file2 })root1.append(root2).toResult().css
variable stringify
let stringify: Stringifier;
Default function to convert a node tree into a CSS string.
function atRule
atRule: (defaults?: AtRuleProps) => AtRule;
Creates a new
AtRule
node.Parameter defaults
Properties for the new node. New at-rule node.
function comment
comment: (defaults?: CommentProps) => Comment;
Creates a new
Comment
node.Parameter defaults
Properties for the new node. New comment node
function decl
decl: (defaults?: DeclarationProps) => Declaration;
Creates a new
Declaration
node.Parameter defaults
Properties for the new node. New declaration node.
function document
document: (defaults?: DocumentProps) => Document;
Creates a new
Document
node.Parameter defaults
Properties for the new node. New document node.
function postcss
postcss: typeof postcss;
Create a new
Processor
instance that will applyplugins
as CSS processors.let postcss = require('postcss')postcss(plugins).process(css, { from, to }).then(result => {console.log(result.css)})Parameter plugins
PostCSS plugins. Processor to process multiple CSS.
function root
root: (defaults?: RootProps) => Root;
Creates a new
Root
node.Parameter defaults
Properties for the new node. New root node.
function rule
rule: (defaults?: RuleProps) => Rule;
Creates a new
Rule
node.Parameter default
Properties for the new node. New rule node.
class AtRule
class AtRule_ extends Container {}
Represents an at-rule.
Once (root, { AtRule }) {let media = new AtRule({ name: 'media', params: 'print' })media.append(…)root.append(media)}If it’s followed in the CSS by a
{}
block, this node will have a nodes property representing its children.const root = postcss.parse('@charset "UTF-8"; @media print {}')const charset = root.firstcharset.type //=> 'atrule'charset.nodes //=> undefinedconst media = root.lastmedia.nodes //=> []
constructor
constructor(defaults?: AtRule.AtRuleProps);
property name
name: string;
The at-rule’s name immediately follows the
@
.const root = postcss.parse('@media print {}')const media = root.firstmedia.name //=> 'media'
property nodes
nodes: Node.ChildNode[];
An array containing the layer’s children.
const root = postcss.parse('@layer example { a { color: black } }')const layer = root.firstlayer.nodes.length //=> 1layer.nodes[0].selector //=> 'a'Can be
undefinded
if the at-rule has no body.const root = postcss.parse('@layer a, b, c;')const layer = root.firstlayer.nodes //=> undefined
property params
params: string;
The at-rule’s parameters, the values that follow the at-rule’s name but precede any
{}
block.const root = postcss.parse('@media print, screen {}')const media = root.firstmedia.params //=> 'print, screen'
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property raws
raws: AtRule.AtRuleRaws;
property type
type: string;
method assign
assign: (overrides: AtRule.AtRuleProps | object) => this;
method clone
clone: (overrides?: Partial<AtRule.AtRuleProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<AtRule.AtRuleProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<AtRule.AtRuleProps>) => this;
class Comment
class Comment_ extends Node {}
It represents a class that handles [CSS comments](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments)
Once (root, { Comment }) {const note = new Comment({ text: 'Note: …' })root.append(note)}Remember that CSS comments inside selectors, at-rule parameters, or declaration values will be stored in the
raws
properties explained above.
constructor
constructor(defaults?: Comment.CommentProps);
property parent
parent: Container<Node.ChildNode>;
property raws
raws: Comment.CommentRaws;
property text
text: string;
The comment's text.
property type
type: string;
method assign
assign: (overrides: Comment.CommentProps | object) => this;
method clone
clone: (overrides?: Partial<Comment.CommentProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Comment.CommentProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Comment.CommentProps>) => this;
class Container
abstract class Container_<Child extends Node = ChildNode> extends Node {}
The
Root
,AtRule
, andRule
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.
property first
readonly first: Node;
The container’s first child.
rule.first === rules.nodes[0]
property last
readonly last: Node;
The container’s last child.
rule.last === rule.nodes[rule.nodes.length - 1]
property nodes
nodes: Child[];
An array containing the container’s children.
const root = postcss.parse('a { color: black }')root.nodes.length //=> 1root.nodes[0].selector //=> 'a'root.nodes[0].nodes[0].prop //=> 'color'
method append
append: (...nodes: Container.NewChild[]) => this;
Inserts new nodes to the end of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })const decl2 = new Declaration({ prop: 'background-color', value: 'white' })rule.append(decl1, decl2)root.append({ name: 'charset', params: '"UTF-8"' }) // at-ruleroot.append({ selector: 'a' }) // rulerule.append({ prop: 'color', value: 'black' }) // declarationrule.append({ text: 'Comment' }) // commentroot.append('a {}')root.first.append('color: black; z-index: 1')Parameter nodes
New nodes. This node for methods chain.
method assign
assign: (overrides: Container.ContainerProps | object) => this;
method clone
clone: (overrides?: Partial<Container.ContainerProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Container.ContainerProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Container.ContainerProps>) => this;
method each
each: ( callback: (node: Child, index: number) => false | void) => false | undefined;
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 orArray#forEach
this iterator is safe if you are mutating the array of child nodes during iteration. PostCSS will adjust the current index to match the mutations.const root = postcss.parse('a { color: black; z-index: 1 }')const rule = root.firstfor (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})Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method every
every: ( condition: (node: Child, index: number, nodes: Child[]) => boolean) => boolean;
Returns
true
if callback returnstrue
for all of the container’s children.const noPrefixes = rule.every(i => i.prop[0] !== '-')Parameter condition
Iterator returns true or false. Is every child pass condition.
method index
index: (child: Child | number) => number;
Returns a
child
’s index within theContainer#nodes
array.rule.index( rule.nodes[2] ) //=> 2Parameter child
Child of the current container. Child index.
method insertAfter
insertAfter: (oldNode: Child | number, newNode: Container.NewChild) => this;
Insert new node after old node within the container.
Parameter oldNode
Child or child’s index.
Parameter newNode
New node. This node for methods chain.
method insertBefore
insertBefore: (oldNode: Child | number, newNode: Container.NewChild) => this;
Insert new node before old node within the container.
rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))Parameter oldNode
Child or child’s index.
Parameter newNode
New node. This node for methods chain.
method normalize
protected normalize: ( nodes: Container.NewChild, sample: Node | undefined, type?: 'prepend' | false) => Child[];
An internal method that converts a NewChild into a list of actual child nodes that can then be added to this container.
This ensures that the nodes' parent is set to this container, that they use the correct prototype chain, and that they're marked as dirty.
Parameter mnodes
The new node or nodes to add.
Parameter sample
A node from whose raws the new node's
before
raw should be taken.Parameter type
This should be set to
'prepend'
if the new nodes will be inserted at the beginning of the container.
method prepend
prepend: (...nodes: Container.NewChild[]) => this;
Inserts new nodes to the start of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })const decl2 = new Declaration({ prop: 'background-color', value: 'white' })rule.prepend(decl1, decl2)root.append({ name: 'charset', params: '"UTF-8"' }) // at-ruleroot.append({ selector: 'a' }) // rulerule.append({ prop: 'color', value: 'black' }) // declarationrule.append({ text: 'Comment' }) // commentroot.append('a {}')root.first.append('color: black; z-index: 1')Parameter nodes
New nodes. This node for methods chain.
method push
push: (child: Child) => this;
Add child to the end of the node.
rule.push(new Declaration({ prop: 'color', value: 'black' }))Parameter child
New node. This node for methods chain.
method removeAll
removeAll: () => this;
Removes all children from the container and cleans their parent properties.
rule.removeAll()rule.nodes.length //=> 0This node for methods chain.
method removeChild
removeChild: (child: Child | number) => this;
Removes node from the container and cleans the parent properties from the node and its children.
rule.nodes.length //=> 5rule.removeChild(decl)rule.nodes.length //=> 4decl.parent //=> undefinedParameter child
Child or child’s index. This node for methods chain.
method replaceValues
replaceValues: { ( pattern: RegExp | string, replaced: string | ((substring: string, ...args: any[]) => string) ): this; ( pattern: string | RegExp, options: Container.ValueOptions, replaced: string | ((substring: string, ...args: any[]) => string) ): this;};
Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.
This method is useful if you are using a custom unit or function and need to iterate through all values.
root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {return 15 * parseInt(string) + 'px'})Parameter pattern
Replace pattern.
Parameter options
Options to speed up the search.
Parameter replaced
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
. This node for methods chain.
method some
some: ( condition: (node: Child, index: number, nodes: Child[]) => boolean) => boolean;
Returns
true
if callback returnstrue
for (at least) one of the container’s children.const hasPrefix = rule.some(i => i.prop[0] === '-')Parameter condition
Iterator returns true or false. Is some child pass condition.
method walk
walk: ( callback: (node: ChildNode, index: number) => false | void) => false | undefined;
Traverses the container’s descendant nodes, calling callback for each node.
Like container.each(), this method is safe to use if you are mutating arrays during iteration.
If you only need to iterate through the container’s immediate children, use
Container#each
.root.walk(node => {// Traverses all descendant nodes.})Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkAtRules
walkAtRules: { ( nameFilter: RegExp | string, callback: (atRule: AtRule, index: number) => false | void ): false | undefined; (callback: (atRule: AtRule, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each at-rule node.
If you pass a filter, iteration will only happen over at-rules that have matching names.
Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.root.walkAtRules(rule => {if (isOld(rule.name)) rule.remove()})let first = falseroot.walkAtRules('charset', rule => {if (!first) {first = true} else {rule.remove()}})Parameter name
String or regular expression to filter at-rules by name.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkComments
walkComments: { (callback: (comment: Comment, indexed: number) => false | void): | false | undefined; (callback: (comment: Comment, indexed: number) => false | void): false;};
method walkDecls
walkDecls: { ( propFilter: RegExp | string, callback: (decl: Declaration, index: number) => false | void ): false | undefined; (callback: (decl: Declaration, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each declaration node.
If you pass a filter, iteration will only happen over declarations with matching properties.
root.walkDecls(decl => {checkPropertySupport(decl.prop)})root.walkDecls('border-radius', decl => {decl.remove()})root.walkDecls(/^background/, decl => {decl.value = takeFirstColorFromGradient(decl.value)})Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.Parameter prop
String or regular expression to filter declarations by property name.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkRules
walkRules: { ( selectorFilter: RegExp | string, callback: (rule: Rule, index: number) => false | void ): false | undefined; (callback: (rule: Rule, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each rule node.
If you pass a filter, iteration will only happen over rules with matching selectors.
Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.const selectors = []root.walkRules(rule => {selectors.push(rule.selector)})console.log(`Your CSS uses ${ selectors.length } selectors`)Parameter selector
String or regular expression to filter rules by selector.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
class CssSyntaxError
class CssSyntaxError_ extends Error {}
The CSS parser throws this error for broken CSS.
Custom parsers can throw this error for broken custom syntax using the
Node#error
method.PostCSS will use the input source map to detect the original error location. If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS, PostCSS will show the original position in the Sass file.
If you need the position in the PostCSS input (e.g., to debug the previous compiler), use
error.input.file
.// Raising error from pluginthrow node.error('Unknown variable', { plugin: 'postcss-vars' })// Catching and checking syntax errortry {postcss.parse('a{')} catch (error) {if (error.name === 'CssSyntaxError') {error //=> CssSyntaxError}}
constructor
constructor( message: string, lineOrStartPos?: number | CssSyntaxError.RangePosition, columnOrEndPos?: number | CssSyntaxError.RangePosition, source?: string, file?: string, plugin?: string);
Instantiates a CSS syntax error. Can be instantiated for a single position or for a range.
Parameter message
Error message.
Parameter lineOrStartPos
If for a single position, the line number, or if for a range, the inclusive start position of the error.
Parameter columnOrEndPos
If for a single position, the column number, or if for a range, the exclusive end position of the error.
Parameter source
Source code of the broken file.
Parameter file
Absolute path to the broken file.
Parameter plugin
PostCSS plugin name, if error came from plugin.
property column
column?: number;
Source column of the error.
error.column //=> 1error.input.column //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.column
.
property endColumn
endColumn?: number;
Source column of the error's end, exclusive. Provided if the error pertains to a range.
error.endColumn //=> 1error.input.endColumn //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.endColumn
.
property endLine
endLine?: number;
Source line of the error's end, exclusive. Provided if the error pertains to a range.
error.endLine //=> 3error.input.endLine //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.endLine
.
property file
file?: string;
Absolute path to the broken file.
error.file //=> 'a.sass'error.input.file //=> 'a.css'PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.file
.
property input
input?: FilePosition;
Input object with PostCSS internal information about input file. If input has source map from previous tool, PostCSS will use origin (for example, Sass) source. You can use this object to get PostCSS input source.
error.input.file //=> 'a.css'error.file //=> 'a.sass'
property line
line?: number;
Source line of the error.
error.line //=> 2error.input.line //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.line
.
property message
message: string;
Full error text in the GNU error format with plugin, file, line and column.
error.message //=> 'a.css:1:1: Unclosed block'
property name
name: string;
Always equal to
'CssSyntaxError'
. You should always check error type byerror.name === 'CssSyntaxError'
instead oferror instanceof CssSyntaxError
, because npm could have several PostCSS versions.if (error.name === 'CssSyntaxError') {error //=> CssSyntaxError}
property plugin
plugin?: string;
Plugin name, if error came from plugin.
error.plugin //=> 'postcss-vars'
property reason
reason: string;
Error message.
error.message //=> 'Unclosed block'
property source
source?: string;
Source code of the broken file.
error.source //=> 'a { b {} }'error.input.source //=> 'a b { }'
property stack
stack: string;
method showSourceCode
showSourceCode: (color?: boolean) => string;
Returns a few lines of CSS source that caused the error.
If the CSS has an input source map without
sourceContent
, this method will return an empty string.error.showSourceCode() //=> " 4 | }// 5 | a {// > 6 | bad// | ^// 7 | }// 8 | b {"Parameter color
Whether arrow will be colored red by terminal color codes. By default, PostCSS will detect color support by
process.stdout.isTTY
andprocess.env.NODE_DISABLE_COLORS
. Few lines of CSS source that caused the error.
method toString
toString: () => string;
Returns error position, message and source code of the broken part.
error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block// > 1 | a {// | ^"Error position, message and source code.
class Declaration
class Declaration_ extends Node {}
It represents a class that handles [CSS declarations](https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_declarations)
Once (root, { Declaration }) {const color = new Declaration({ prop: 'color', value: 'black' })root.append(color)}const root = postcss.parse('a { color: black }')const decl = root.first?.firstdecl.type //=> 'decl'decl.toString() //=> ' color: black'
constructor
constructor(defaults?: Declaration.DeclarationProps);
property important
important: boolean;
It represents a specificity of the declaration.
If true, the CSS declaration will have an [important](https://developer.mozilla.org/en-US/docs/Web/CSS/important) specifier.
const root = postcss.parse('a { color: black !important; color: red }')root.first.first.important //=> trueroot.first.last.important //=> undefined
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property prop
prop: string;
The property name for a CSS declaration.
const root = postcss.parse('a { color: black }')const decl = root.first.firstdecl.prop //=> 'color'
property raws
raws: Declaration.DeclarationRaws;
property type
type: string;
property value
value: string;
The property value for a CSS declaration.
Any CSS comments inside the value string will be filtered out. CSS comments present in the source value will be available in the
raws
property.Assigning new
value
would ignore the comments inraws
property while compiling node to string.const root = postcss.parse('a { color: black }')const decl = root.first.firstdecl.value //=> 'black'
property variable
readonly variable: boolean;
It represents a getter that returns
true
if a declaration starts with--
or$
, which are used to declare variables in CSS and SASS/SCSS.const root = postcss.parse(':root { --one: 1 }')const one = root.first.firstone.variable //=> trueconst root = postcss.parse('$one: 1')const one = root.firstone.variable //=> true
method assign
assign: (overrides: Declaration.DeclarationProps | object) => this;
method clone
clone: (overrides?: Partial<Declaration.DeclarationProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Declaration.DeclarationProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Declaration.DeclarationProps>) => this;
class Document
class Document_ extends Container<Root> {}
Represents a file and contains all its parsed nodes.
**Experimental:** some aspects of this node could change within minor or patch version releases.
const document = htmlParser('<html><style>a{color:black}</style><style>b{z-index:2}</style>')document.type //=> 'document'document.nodes.length //=> 2
constructor
constructor(defaults?: Document.DocumentProps);
property nodes
nodes: Root[];
property parent
parent: undefined;
property type
type: string;
method assign
assign: (overrides: Document.DocumentProps | object) => this;
method clone
clone: (overrides?: Partial<Document.DocumentProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Document.DocumentProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Document.DocumentProps>) => this;
method toResult
toResult: (options?: ProcessOptions) => Result;
Returns a
Result
instance representing the document’s CSS roots.const root1 = postcss.parse(css1, { from: 'a.css' })const root2 = postcss.parse(css2, { from: 'b.css' })const document = postcss.document()document.append(root1)document.append(root2)const result = document.toResult({ to: 'all.css', map: true })Parameter opts
Options. Result with current document’s CSS.
class Input
class Input_ {}
Represents the source CSS.
const root = postcss.parse(css, { from: file })const input = root.source.input
constructor
constructor(css: string, opts?: ProcessOptions<Document_ | Root_>);
Parameter css
Input CSS source.
Parameter opts
Process options.
property css
css: string;
Input CSS source.
const input = postcss.parse('a{}', { from: file }).inputinput.css //=> "a{}"
property file
file?: string;
The absolute path to the CSS source file defined with the
from
option.const root = postcss.parse(css, { from: 'a.css' })root.source.input.file //=> '/home/ai/a.css'
property from
readonly from: string;
The CSS source identifier. Contains
Input#file
if the user set thefrom
option, orInput#id
if they did not.const root = postcss.parse(css, { from: 'a.css' })root.source.input.from //=> "/home/ai/a.css"const root = postcss.parse(css)root.source.input.from //=> "<input css 1>"
property hasBOM
hasBOM: boolean;
The flag to indicate whether or not the source code has Unicode BOM.
property id
id?: string;
The unique ID of the CSS source. It will be created if
from
option is not provided (because PostCSS does not know the file path).const root = postcss.parse(css)root.source.input.file //=> undefinedroot.source.input.id //=> "<input css 8LZeVF>"
property map
map: PreviousMap;
The input source map passed from a compilation step before PostCSS (for example, from Sass compiler).
root.source.input.map.consumer().sources //=> ['a.sass']
method error
error: { ( message: string, start: { column: number; line: number } | { offset: number }, end: { column: number; line: number } | { offset: number }, opts?: { plugin?: CssSyntaxError['plugin'] } ): CssSyntaxError; ( message: string, line: number, column: number, opts?: { plugin?: string } ): CssSyntaxError; ( message: string, offset: number, opts?: { plugin?: string } ): CssSyntaxError;};
Returns
CssSyntaxError
with information about the error and its position.
method fromOffset
fromOffset: (offset: number) => { col: number; line: number } | null;
Converts source offset to line and column.
Parameter offset
Source offset.
method origin
origin: ( line: number, column: number, endLine?: number, endColumn?: number) => false | Input.FilePosition;
Reads the input source map and returns a symbol position in the input source (e.g., in a Sass file that was compiled to CSS before being passed to PostCSS). Optionally takes an end position, exclusive.
root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }root.source.input.origin(1, 1, 1, 4)//=> { file: 'a.css', line: 3, column: 1, endLine: 3, endColumn: 4 }Parameter line
Line for inclusive start position in input CSS.
Parameter column
Column for inclusive start position in input CSS.
Parameter endLine
Line for exclusive end position in input CSS.
Parameter endColumn
Column for exclusive end position in input CSS.
Position in input source.
method toJSON
toJSON: () => object;
Converts this to a JSON-friendly object representation.
class LazyResult
class LazyResult_<RootNode = Document | Root> implements PromiseLike<Result<RootNode>> {}
A Promise proxy for the result of PostCSS transformations.
A
LazyResult
instance is returned byProcessor#process
.const lazy = postcss([autoprefixer]).process(css)
constructor
constructor(processor: Processor, css: string, opts: ResultOptions);
Parameter processor
Processor used for this transformation.
Parameter css
CSS to parse and transform.
Parameter opts
Options from the
Processor#process
orRoot#toResult
.
property [Symbol.toStringTag]
readonly [Symbol.toStringTag]: string;
Returns the default string description of an object. Required to implement the Promise interface.
property catch
catch: <TResult = never>( onrejected?: (reason: any) => TResult | PromiseLike<TResult>) => Promise<Result<RootNode> | TResult>;
Processes input CSS through synchronous and asynchronous plugins and calls onRejected for each error thrown in any plugin.
It implements standard Promise API.
postcss([autoprefixer]).process(css).then(result => {console.log(result.css)}).catch(error => {console.error(error)})
property content
readonly content: string;
An alias for the
css
property. Use it with syntaxes that generate non-CSS output.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property css
readonly css: string;
Processes input CSS through synchronous plugins, converts
Root
to a CSS string and returnsResult#css
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property finally
finally: (onfinally?: () => void) => Promise<Result<RootNode>>;
Processes input CSS through synchronous and asynchronous plugins and calls onFinally on any error or when all plugins will finish work.
It implements standard Promise API.
postcss([autoprefixer]).process(css).finally(() => {console.log('processing ended')})
property map
readonly map: any;
Processes input CSS through synchronous plugins and returns
Result#map
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property messages
readonly messages: Message[];
Processes input CSS through synchronous plugins and returns
Result#messages
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property opts
readonly opts: ResultOptions;
Options from the
Processor#process
call.
property processor
readonly processor: Processor;
Returns a
Processor
instance, which will be used for CSS transformations.
property root
readonly root: {};
Processes input CSS through synchronous plugins and returns
Result#root
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property then
then: <TResult1 = Result<RootNode>, TResult2 = never>( onfulfilled?: (value: Result<RootNode>) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<TResult1 | TResult2>;
Processes input CSS through synchronous and asynchronous plugins and calls
onFulfilled
with a Result instance. If a plugin throws an error, theonRejected
callback will be executed.It implements standard Promise API.
postcss([autoprefixer]).process(css, { from: cssPath }).then(result => {console.log(result.css)})
method async
async: () => Promise<Result<RootNode>>;
Run plugin in async way and return
Result
.Result with output content.
method sync
sync: () => Result<RootNode>;
Run plugin in sync way and return
Result
.Result with output content.
method toString
toString: () => string;
Alias for the
LazyResult#css
property.lazy + '' === lazy.cssOutput CSS.
method warnings
warnings: () => Warning[];
Processes input CSS through synchronous plugins and calls
Result#warnings
.Warnings from plugins.
class Node
class Node extends Node_ {}
class Processor
class Processor_ {}
Contains plugins to process CSS. Create one
Processor
instance, initialize its plugins, and then use that instance on numerous CSS files.const processor = postcss([autoprefixer, postcssNested])processor.process(css1).then(result => console.log(result.css))processor.process(css2).then(result => console.log(result.css))
constructor
constructor(plugins?: readonly AcceptedPlugin[]);
Parameter plugins
PostCSS plugins
property plugins
plugins: (Plugin | TransformCallback | Transformer)[];
Plugins added to this processor.
const processor = postcss([autoprefixer, postcssNested])processor.plugins.length //=> 2
property version
version: string;
Current PostCSS version.
if (result.processor.version.split('.')[0] !== '6') {throw new Error('This plugin works only with PostCSS 6')}
method process
process: { (css: { toString(): string } | LazyResult | Result | Root | string): | LazyResult | NoWorkResult; <RootNode extends Document | Root = Root>( css: | string | Root | Result<Document | Root> | LazyResult<Document | Root> | { toString(): string }, options: ProcessOptions<RootNode> ): LazyResult<RootNode>;};
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 theLazyResult
methods.processor.process(css, { from: 'a.css', to: 'a.out.css' }).then(result => {console.log(result.css)})Parameter css
String with input CSS or any object with a
toString()
method, like a Buffer. Optionally, send aResult
instance and the processor will take theRoot
from it.Parameter opts
Options. Promise proxy.
method use
use: (plugin: AcceptedPlugin) => this;
Adds a plugin to be used as a CSS processor.
PostCSS plugin can be in 4 formats: * A plugin in
Plugin
format. * A plugin creator function withpluginCreator.postcss = true
. PostCSS will call this function without argument to get plugin. * A function. PostCSS will pass the function a Root as the first argument and currentResult
instance as the second. * AnotherProcessor
instance. PostCSS will copy plugins from that instance into this one.Plugins can also be added by passing them as arguments when creating a
postcss
instance (see [postcss(plugins)
]).Asynchronous plugins should return a
Promise
instance.const processor = postcss().use(autoprefixer).use(postcssNested)Parameter plugin
PostCSS plugin or
Processor
with plugins. Current processor to make methods chain.
class Result
class Result_<RootNode = Document | Root> {}
Provides the result of the PostCSS transformations.
A Result instance is returned by
LazyResult#then
orRoot#toResult
methods.postcss([autoprefixer]).process(css).then(result => {console.log(result.css)})const result2 = postcss.parse(css).toResult()
constructor
constructor(processor: Processor, root: {}, opts: Result.ResultOptions);
Parameter processor
Processor used for this transformation.
Parameter root
Root node after all transformations.
Parameter opts
Options from the
Processor#process
orRoot#toResult
.
property content
readonly content: string;
An alias for the
Result#css
property. Use it with syntaxes that generate non-CSS output.result.css === result.content
property css
css: string;
A CSS string representing of
Result#root
.postcss.parse('a{}').toResult().css //=> "a{}"
property lastPlugin
lastPlugin: Plugin | TransformCallback;
Last runned PostCSS plugin.
property map
map: any;
An instance of
SourceMapGenerator
class from thesource-map
library, representing changes to theResult#root
instance.result.map.toJSON() //=> { version: 3, file: 'a.css', … }if (result.map) {fs.writeFileSync(result.opts.to + '.map', result.map.toString())}
property messages
messages: Result.Message[];
Contains messages from plugins (e.g., warnings or custom messages). Each message should have type and plugin properties.
AtRule: {import: (atRule, { result }) {const importedFile = parseImport(atRule)result.messages.push({type: 'dependency',plugin: 'postcss-import',file: importedFile,parent: result.opts.from})}}
property opts
opts: Result.ResultOptions;
Options from the
Processor#process
orRoot#toResult
call that produced this Result instance.]root.toResult(opts).opts === opts
property processor
processor: Processor;
The Processor instance used for this transformation.
for (const plugin of result.processor.plugins) {if (plugin.postcssPlugin === 'postcss-bad') {throw 'postcss-good is incompatible with postcss-bad'}})
property root
root: {};
Root node after all transformations.
root.toResult().root === root
method toString
toString: () => string;
Returns for
Result#css
content.result + '' === result.cssString representing of
Result#root
.
method warn
warn: (message: string, options?: WarningOptions) => Warning;
Creates an instance of
Warning
and adds it toResult#messages
.if (decl.important) {result.warn('Avoid !important', { node: decl, word: '!important' })}Parameter text
Warning message.
Parameter opts
Warning options. Created warning.
method warnings
warnings: () => Warning[];
Returns warnings from plugins. Filters
Warning
instances fromResult#messages
.result.warnings().forEach(warn => {console.warn(warn.toString())})Warnings from plugins.
class Root
class Root_ extends Container {}
Represents a CSS file and contains all its parsed nodes.
const root = postcss.parse('a{color:black} b{z-index:2}')root.type //=> 'root'root.nodes.length //=> 2
constructor
constructor(defaults?: Root.RootProps);
property nodes
nodes: Node.ChildNode[];
property parent
parent: Document;
property raws
raws: Root.RootRaws;
property type
type: string;
method assign
assign: (overrides: object | Root.RootProps) => this;
method clone
clone: (overrides?: Partial<Root.RootProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Root.RootProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Root.RootProps>) => this;
method toResult
toResult: (options?: ProcessOptions) => Result;
Returns a
Result
instance representing the root’s CSS.const root1 = postcss.parse(css1, { from: 'a.css' })const root2 = postcss.parse(css2, { from: 'b.css' })root1.append(root2)const result = root1.toResult({ to: 'all.css', map: true })Parameter options
Options. Result with current root’s CSS.
class Rule
class Rule_ extends Container {}
Represents a CSS rule: a selector followed by a declaration block.
Once (root, { Rule }) {let a = new Rule({ selector: 'a' })a.append(…)root.append(a)}const root = postcss.parse('a{}')const rule = root.firstrule.type //=> 'rule'rule.toString() //=> 'a{}'
constructor
constructor(defaults?: Rule.RuleProps);
property nodes
nodes: Node.ChildNode[];
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property raws
raws: Rule.RuleRaws;
property selector
selector: string;
The rule’s full selector represented as a string.
const root = postcss.parse('a, b { }')const rule = root.firstrule.selector //=> 'a, b'
property selectors
selectors: string[];
An array containing the rule’s individual selectors. Groups of selectors are split at commas.
const root = postcss.parse('a, b { }')const rule = root.firstrule.selector //=> 'a, b'rule.selectors //=> ['a', 'b']rule.selectors = ['a', 'strong']rule.selector //=> 'a, strong'
property type
type: string;
method assign
assign: (overrides: object | Rule.RuleProps) => this;
method clone
clone: (overrides?: Partial<Rule.RuleProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Rule.RuleProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Rule.RuleProps>) => this;
class Warning
class Warning_ {}
Represents a plugin’s warning. It can be created using
Node#warn
.if (decl.important) {decl.warn(result, 'Avoid !important', { word: '!important' })}
constructor
constructor(text: string, opts?: Warning.WarningOptions);
Parameter text
Warning message.
Parameter opts
Warning options.
property column
column: number;
Column for inclusive start position in the input file with this warning’s source.
warning.column //=> 6
property endColumn
endColumn?: number;
Column for exclusive end position in the input file with this warning’s source.
warning.endColumn //=> 4
property endLine
endLine?: number;
Line for exclusive end position in the input file with this warning’s source.
warning.endLine //=> 6
property line
line: number;
Line for inclusive start position in the input file with this warning’s source.
warning.line //=> 5
property node
node: Node;
Contains the CSS node that caused the warning.
warning.node.toString() //=> 'color: white !important'
property plugin
plugin: string;
The name of the plugin that created this warning. When you call
Node#warn
it will fill this property automatically.warning.plugin //=> 'postcss-important'
property text
text: string;
The warning message.
warning.text //=> 'Try to avoid !important'
property type
type: string;
Type to filter warnings from
Result#messages
. Always equal to"warning"
.
method toString
toString: () => string;
Returns a warning position and message.
warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'Warning position and message.
interface AtRuleProps
interface AtRuleProps extends ContainerProps {}
interface Builder
interface Builder {}
call signature
(part: string, node?: AnyNode, type?: 'end' | 'start'): void;
interface CommentProps
interface CommentProps extends NodeProps {}
interface ContainerProps
interface ContainerProps extends NodeProps {}
property nodes
nodes?: readonly (ChildProps | Node)[];
interface DeclarationProps
interface DeclarationProps {}
property important
important?: boolean;
Whether the declaration has an
!important
annotation.
property prop
prop: string;
Name of the declaration.
property raws
raws?: DeclarationRaws;
Information used to generate byte-to-byte equal node string as it was in the origin input.
property value
value: string;
Value of the declaration.
interface DocumentProps
interface DocumentProps extends ContainerProps {}
interface FilePosition
interface FilePosition {}
property column
column: number;
Column of inclusive start position in source file.
property endColumn
endColumn?: number;
Column of exclusive end position in source file.
property endLine
endLine?: number;
Line of exclusive end position in source file.
property file
file?: string;
Absolute path to the source file.
property line
line: number;
Line of inclusive start position in source file.
property source
source?: string;
Source code.
property url
url: string;
URL for the source file.
interface JSONHydrator
interface JSONHydrator {}
call signature
(data: object): Node;
call signature
(data: object[]): Node[];
interface Message
interface Message {}
property plugin
plugin?: string;
Source PostCSS plugin name.
property type
type: string;
Message type.
index signature
[others: string]: any;
interface NodeErrorOptions
interface NodeErrorOptions {}
property endIndex
endIndex?: number;
An ending index inside a node's string that should be highlighted as source of error.
property index
index?: number;
An index inside a node's string that should be highlighted as source of error.
property plugin
plugin?: string;
Plugin name that created this error. PostCSS will set it automatically.
property word
word?: string;
A word inside a node's string, that should be highlighted as source of error.
interface NodeProps
interface NodeProps {}
Interface represents an interface for an object received as parameter by Node class constructor.
property source
source?: Source;
interface OldPlugin
interface OldPlugin<T> extends Transformer {}
property postcss
postcss: Transformer;
call signature
(opts?: T): Transformer;
interface Parser
interface Parser<RootNode = Document | Root> {}
call signature
( css: { toString(): string } | string, opts?: Pick<ProcessOptions, 'from' | 'map'>): RootNode;
interface Plugin
interface Plugin extends Processors {}
property postcssPlugin
postcssPlugin: string;
property prepare
prepare?: (result: Result) => Processors;
interface PluginCreator
interface PluginCreator<PluginOptions> {}
property postcss
postcss: true;
call signature
(opts?: PluginOptions): Plugin | Processor;
interface Position
interface Position {}
interface ProcessOptions
interface ProcessOptions<RootNode = Document | Root> {}
property from
from?: string | undefined;
The path of the CSS source file. You should always set
from
, because it is used in source map generation and syntax error messages.
property map
map?: boolean | SourceMapOptions;
Source map options
property parser
parser?: Parser<RootNode> | Syntax<RootNode>;
Function to generate AST by string.
property stringifier
stringifier?: Stringifier | Syntax<RootNode>;
Class to generate string by AST.
property syntax
syntax?: Syntax<RootNode>;
Object with parse and stringify.
property to
to?: string;
The path where you'll put the output CSS file. You should always set
to
to generate correct source maps.
interface RootProps
interface RootProps extends ContainerProps {}
property raws
raws?: RootRaws;
Information used to generate byte-to-byte equal node string as it was in the origin input.
interface Source
interface Source {}
Source represents an interface for the Node.source property.
interface SourceMapOptions
interface SourceMapOptions {}
property absolute
absolute?: boolean;
Use absolute path in generated source map.
property annotation
annotation?: ((file: string, root: Root) => string) | boolean | string;
Indicates that PostCSS should add annotation comments to the CSS. By default, PostCSS will always add a comment with a path to the source map. PostCSS will not add annotations to CSS files that do not contain any comments.
By default, PostCSS presumes that you want to save the source map as
opts.to + '.map'
and will use this path in the annotation comment. A different path can be set by providing a string value for annotation.If you have set
inline: true
, annotation cannot be disabled.
property from
from?: string;
Override
from
in map’s sources.
property inline
inline?: boolean;
Indicates that the source map should be embedded in the output CSS as a Base64-encoded comment. By default, it is
true
. But if all previous maps are external, not inline, PostCSS will not embed the map even if you do not set this option.If you have an inline source map, the result.map property will be empty, as the source map will be contained within the text of
result.css
.
property prev
prev?: ((file: string) => string) | boolean | object | string;
Source map content from a previous processing step (e.g., Sass).
PostCSS will try to read the previous source map automatically (based on comments within the source CSS), but you can use this option to identify it manually.
If desired, you can omit the previous map with prev:
false
.
property sourcesContent
sourcesContent?: boolean;
Indicates that PostCSS should set the origin content (e.g., Sass source) of the source map. By default, it is true. But if all previous maps do not contain sources content, PostCSS will also leave it out even if you do not set this option.
interface Stringifier
interface Stringifier {}
call signature
(node: AnyNode, builder: Builder): void;
interface Syntax
interface Syntax<RootNode = Document | Root> {}
interface TransformCallback
interface TransformCallback {}
call signature
(root: Root, result: Result): Promise<void> | void;
interface Transformer
interface Transformer extends TransformCallback {}
property postcssPlugin
postcssPlugin: string;
property postcssVersion
postcssVersion: string;
interface WarningOptions
interface WarningOptions {}
property end
end?: RangePosition;
End position, exclusive, in CSS node string that caused the warning.
property endIndex
endIndex?: number;
End index, exclusive, in CSS node string that caused the warning.
property index
index?: number;
Start index, inclusive, in CSS node string that caused the warning.
property node
node?: Node;
CSS node that caused the warning.
property plugin
plugin?: string;
Name of the plugin that created this warning.
Result#warn
fills this property automatically.
property start
start?: RangePosition;
Start position, inclusive, in CSS node string that caused the warning.
property word
word?: string;
Word in CSS source that caused the warning.
type AcceptedPlugin
type AcceptedPlugin = | { postcss: Processor | TransformCallback; } | OldPlugin<any> | Plugin | PluginCreator<any> | Processor | TransformCallback;
type AnyNode
type AnyNode = AtRule.default | Comment | Declaration | Document | Root | Rule;
type ChildNode
type ChildNode = AtRule.default | Comment | Declaration | Rule;
type ChildProps
type ChildProps = AtRuleProps | CommentProps | DeclarationProps | RuleProps;
type Helpers
type Helpers = { postcss: Postcss; result: Result } & Postcss;
type NewChild
type NewChild = | ChildProps | Node | readonly ChildProps[] | readonly Node[] | readonly string[] | string | undefined;
All types that can be passed into container methods to create or add a new child node.
type Postcss
type Postcss = typeof postcss;
type RuleProps
type RuleProps = { /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ raws?: RuleRaws;} & ( | { /** Selector or selectors of the rule. */ selector: string; selectors?: never; } | { selector?: never; /** Selectors of the rule represented as an array of strings. */ selectors: readonly string[]; }) & ContainerProps;
type SourceMap
type SourceMap = { toJSON(): RawSourceMap;} & SourceMapGenerator;
namespace postcss.postcss
namespace postcss.postcss {}
variable fromJSON
let fromJSON: JSONHydrator;
Rehydrate a JSON AST (from
Node#toJSON
) back into the AST classes.const json = root.toJSON()// save to file, send by network, etcconst root2 = postcss.fromJSON(json)
variable parse
let parse: Parser<Root>;
Parses source css and returns a new
Root
orDocument
node, which contains the source CSS nodes.// Simple CSS concatenation with source map supportconst root1 = postcss.parse(css1, { from: file1 })const root2 = postcss.parse(css2, { from: file2 })root1.append(root2).toResult().css
variable stringify
let stringify: Stringifier;
Default function to convert a node tree into a CSS string.
function atRule
atRule: (defaults?: AtRuleProps) => AtRule;
Creates a new
AtRule
node.Parameter defaults
Properties for the new node. New at-rule node.
function comment
comment: (defaults?: CommentProps) => Comment;
Creates a new
Comment
node.Parameter defaults
Properties for the new node. New comment node
function decl
decl: (defaults?: DeclarationProps) => Declaration;
Creates a new
Declaration
node.Parameter defaults
Properties for the new node. New declaration node.
function document
document: (defaults?: DocumentProps) => Document;
Creates a new
Document
node.Parameter defaults
Properties for the new node. New document node.
function postcss
postcss: typeof postcss;
Create a new
Processor
instance that will applyplugins
as CSS processors.let postcss = require('postcss')postcss(plugins).process(css, { from, to }).then(result => {console.log(result.css)})Parameter plugins
PostCSS plugins. Processor to process multiple CSS.
function root
root: (defaults?: RootProps) => Root;
Creates a new
Root
node.Parameter defaults
Properties for the new node. New root node.
function rule
rule: (defaults?: RuleProps) => Rule;
Creates a new
Rule
node.Parameter default
Properties for the new node. New rule node.
class AtRule
class AtRule_ extends Container {}
Represents an at-rule.
Once (root, { AtRule }) {let media = new AtRule({ name: 'media', params: 'print' })media.append(…)root.append(media)}If it’s followed in the CSS by a
{}
block, this node will have a nodes property representing its children.const root = postcss.parse('@charset "UTF-8"; @media print {}')const charset = root.firstcharset.type //=> 'atrule'charset.nodes //=> undefinedconst media = root.lastmedia.nodes //=> []
constructor
constructor(defaults?: AtRule.AtRuleProps);
property name
name: string;
The at-rule’s name immediately follows the
@
.const root = postcss.parse('@media print {}')const media = root.firstmedia.name //=> 'media'
property nodes
nodes: Node.ChildNode[];
An array containing the layer’s children.
const root = postcss.parse('@layer example { a { color: black } }')const layer = root.firstlayer.nodes.length //=> 1layer.nodes[0].selector //=> 'a'Can be
undefinded
if the at-rule has no body.const root = postcss.parse('@layer a, b, c;')const layer = root.firstlayer.nodes //=> undefined
property params
params: string;
The at-rule’s parameters, the values that follow the at-rule’s name but precede any
{}
block.const root = postcss.parse('@media print, screen {}')const media = root.firstmedia.params //=> 'print, screen'
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property raws
raws: AtRule.AtRuleRaws;
property type
type: string;
method assign
assign: (overrides: AtRule.AtRuleProps | object) => this;
method clone
clone: (overrides?: Partial<AtRule.AtRuleProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<AtRule.AtRuleProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<AtRule.AtRuleProps>) => this;
class Comment
class Comment_ extends Node {}
It represents a class that handles [CSS comments](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments)
Once (root, { Comment }) {const note = new Comment({ text: 'Note: …' })root.append(note)}Remember that CSS comments inside selectors, at-rule parameters, or declaration values will be stored in the
raws
properties explained above.
constructor
constructor(defaults?: Comment.CommentProps);
property parent
parent: Container<Node.ChildNode>;
property raws
raws: Comment.CommentRaws;
property text
text: string;
The comment's text.
property type
type: string;
method assign
assign: (overrides: Comment.CommentProps | object) => this;
method clone
clone: (overrides?: Partial<Comment.CommentProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Comment.CommentProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Comment.CommentProps>) => this;
class Container
abstract class Container_<Child extends Node = ChildNode> extends Node {}
The
Root
,AtRule
, andRule
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.
property first
readonly first: Node;
The container’s first child.
rule.first === rules.nodes[0]
property last
readonly last: Node;
The container’s last child.
rule.last === rule.nodes[rule.nodes.length - 1]
property nodes
nodes: Child[];
An array containing the container’s children.
const root = postcss.parse('a { color: black }')root.nodes.length //=> 1root.nodes[0].selector //=> 'a'root.nodes[0].nodes[0].prop //=> 'color'
method append
append: (...nodes: Container.NewChild[]) => this;
Inserts new nodes to the end of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })const decl2 = new Declaration({ prop: 'background-color', value: 'white' })rule.append(decl1, decl2)root.append({ name: 'charset', params: '"UTF-8"' }) // at-ruleroot.append({ selector: 'a' }) // rulerule.append({ prop: 'color', value: 'black' }) // declarationrule.append({ text: 'Comment' }) // commentroot.append('a {}')root.first.append('color: black; z-index: 1')Parameter nodes
New nodes. This node for methods chain.
method assign
assign: (overrides: Container.ContainerProps | object) => this;
method clone
clone: (overrides?: Partial<Container.ContainerProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Container.ContainerProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Container.ContainerProps>) => this;
method each
each: ( callback: (node: Child, index: number) => false | void) => false | undefined;
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 orArray#forEach
this iterator is safe if you are mutating the array of child nodes during iteration. PostCSS will adjust the current index to match the mutations.const root = postcss.parse('a { color: black; z-index: 1 }')const rule = root.firstfor (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})Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method every
every: ( condition: (node: Child, index: number, nodes: Child[]) => boolean) => boolean;
Returns
true
if callback returnstrue
for all of the container’s children.const noPrefixes = rule.every(i => i.prop[0] !== '-')Parameter condition
Iterator returns true or false. Is every child pass condition.
method index
index: (child: Child | number) => number;
Returns a
child
’s index within theContainer#nodes
array.rule.index( rule.nodes[2] ) //=> 2Parameter child
Child of the current container. Child index.
method insertAfter
insertAfter: (oldNode: Child | number, newNode: Container.NewChild) => this;
Insert new node after old node within the container.
Parameter oldNode
Child or child’s index.
Parameter newNode
New node. This node for methods chain.
method insertBefore
insertBefore: (oldNode: Child | number, newNode: Container.NewChild) => this;
Insert new node before old node within the container.
rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))Parameter oldNode
Child or child’s index.
Parameter newNode
New node. This node for methods chain.
method normalize
protected normalize: ( nodes: Container.NewChild, sample: Node | undefined, type?: 'prepend' | false) => Child[];
An internal method that converts a NewChild into a list of actual child nodes that can then be added to this container.
This ensures that the nodes' parent is set to this container, that they use the correct prototype chain, and that they're marked as dirty.
Parameter mnodes
The new node or nodes to add.
Parameter sample
A node from whose raws the new node's
before
raw should be taken.Parameter type
This should be set to
'prepend'
if the new nodes will be inserted at the beginning of the container.
method prepend
prepend: (...nodes: Container.NewChild[]) => this;
Inserts new nodes to the start of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })const decl2 = new Declaration({ prop: 'background-color', value: 'white' })rule.prepend(decl1, decl2)root.append({ name: 'charset', params: '"UTF-8"' }) // at-ruleroot.append({ selector: 'a' }) // rulerule.append({ prop: 'color', value: 'black' }) // declarationrule.append({ text: 'Comment' }) // commentroot.append('a {}')root.first.append('color: black; z-index: 1')Parameter nodes
New nodes. This node for methods chain.
method push
push: (child: Child) => this;
Add child to the end of the node.
rule.push(new Declaration({ prop: 'color', value: 'black' }))Parameter child
New node. This node for methods chain.
method removeAll
removeAll: () => this;
Removes all children from the container and cleans their parent properties.
rule.removeAll()rule.nodes.length //=> 0This node for methods chain.
method removeChild
removeChild: (child: Child | number) => this;
Removes node from the container and cleans the parent properties from the node and its children.
rule.nodes.length //=> 5rule.removeChild(decl)rule.nodes.length //=> 4decl.parent //=> undefinedParameter child
Child or child’s index. This node for methods chain.
method replaceValues
replaceValues: { ( pattern: RegExp | string, replaced: string | ((substring: string, ...args: any[]) => string) ): this; ( pattern: string | RegExp, options: Container.ValueOptions, replaced: string | ((substring: string, ...args: any[]) => string) ): this;};
Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.
This method is useful if you are using a custom unit or function and need to iterate through all values.
root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {return 15 * parseInt(string) + 'px'})Parameter pattern
Replace pattern.
Parameter options
Options to speed up the search.
Parameter replaced
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
. This node for methods chain.
method some
some: ( condition: (node: Child, index: number, nodes: Child[]) => boolean) => boolean;
Returns
true
if callback returnstrue
for (at least) one of the container’s children.const hasPrefix = rule.some(i => i.prop[0] === '-')Parameter condition
Iterator returns true or false. Is some child pass condition.
method walk
walk: ( callback: (node: ChildNode, index: number) => false | void) => false | undefined;
Traverses the container’s descendant nodes, calling callback for each node.
Like container.each(), this method is safe to use if you are mutating arrays during iteration.
If you only need to iterate through the container’s immediate children, use
Container#each
.root.walk(node => {// Traverses all descendant nodes.})Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkAtRules
walkAtRules: { ( nameFilter: RegExp | string, callback: (atRule: AtRule, index: number) => false | void ): false | undefined; (callback: (atRule: AtRule, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each at-rule node.
If you pass a filter, iteration will only happen over at-rules that have matching names.
Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.root.walkAtRules(rule => {if (isOld(rule.name)) rule.remove()})let first = falseroot.walkAtRules('charset', rule => {if (!first) {first = true} else {rule.remove()}})Parameter name
String or regular expression to filter at-rules by name.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkComments
walkComments: { (callback: (comment: Comment, indexed: number) => false | void): | false | undefined; (callback: (comment: Comment, indexed: number) => false | void): false;};
method walkDecls
walkDecls: { ( propFilter: RegExp | string, callback: (decl: Declaration, index: number) => false | void ): false | undefined; (callback: (decl: Declaration, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each declaration node.
If you pass a filter, iteration will only happen over declarations with matching properties.
root.walkDecls(decl => {checkPropertySupport(decl.prop)})root.walkDecls('border-radius', decl => {decl.remove()})root.walkDecls(/^background/, decl => {decl.value = takeFirstColorFromGradient(decl.value)})Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.Parameter prop
String or regular expression to filter declarations by property name.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkRules
walkRules: { ( selectorFilter: RegExp | string, callback: (rule: Rule, index: number) => false | void ): false | undefined; (callback: (rule: Rule, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each rule node.
If you pass a filter, iteration will only happen over rules with matching selectors.
Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.const selectors = []root.walkRules(rule => {selectors.push(rule.selector)})console.log(`Your CSS uses ${ selectors.length } selectors`)Parameter selector
String or regular expression to filter rules by selector.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
class CssSyntaxError
class CssSyntaxError_ extends Error {}
The CSS parser throws this error for broken CSS.
Custom parsers can throw this error for broken custom syntax using the
Node#error
method.PostCSS will use the input source map to detect the original error location. If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS, PostCSS will show the original position in the Sass file.
If you need the position in the PostCSS input (e.g., to debug the previous compiler), use
error.input.file
.// Raising error from pluginthrow node.error('Unknown variable', { plugin: 'postcss-vars' })// Catching and checking syntax errortry {postcss.parse('a{')} catch (error) {if (error.name === 'CssSyntaxError') {error //=> CssSyntaxError}}
constructor
constructor( message: string, lineOrStartPos?: number | CssSyntaxError.RangePosition, columnOrEndPos?: number | CssSyntaxError.RangePosition, source?: string, file?: string, plugin?: string);
Instantiates a CSS syntax error. Can be instantiated for a single position or for a range.
Parameter message
Error message.
Parameter lineOrStartPos
If for a single position, the line number, or if for a range, the inclusive start position of the error.
Parameter columnOrEndPos
If for a single position, the column number, or if for a range, the exclusive end position of the error.
Parameter source
Source code of the broken file.
Parameter file
Absolute path to the broken file.
Parameter plugin
PostCSS plugin name, if error came from plugin.
property column
column?: number;
Source column of the error.
error.column //=> 1error.input.column //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.column
.
property endColumn
endColumn?: number;
Source column of the error's end, exclusive. Provided if the error pertains to a range.
error.endColumn //=> 1error.input.endColumn //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.endColumn
.
property endLine
endLine?: number;
Source line of the error's end, exclusive. Provided if the error pertains to a range.
error.endLine //=> 3error.input.endLine //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.endLine
.
property file
file?: string;
Absolute path to the broken file.
error.file //=> 'a.sass'error.input.file //=> 'a.css'PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.file
.
property input
input?: FilePosition;
Input object with PostCSS internal information about input file. If input has source map from previous tool, PostCSS will use origin (for example, Sass) source. You can use this object to get PostCSS input source.
error.input.file //=> 'a.css'error.file //=> 'a.sass'
property line
line?: number;
Source line of the error.
error.line //=> 2error.input.line //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.line
.
property message
message: string;
Full error text in the GNU error format with plugin, file, line and column.
error.message //=> 'a.css:1:1: Unclosed block'
property name
name: string;
Always equal to
'CssSyntaxError'
. You should always check error type byerror.name === 'CssSyntaxError'
instead oferror instanceof CssSyntaxError
, because npm could have several PostCSS versions.if (error.name === 'CssSyntaxError') {error //=> CssSyntaxError}
property plugin
plugin?: string;
Plugin name, if error came from plugin.
error.plugin //=> 'postcss-vars'
property reason
reason: string;
Error message.
error.message //=> 'Unclosed block'
property source
source?: string;
Source code of the broken file.
error.source //=> 'a { b {} }'error.input.source //=> 'a b { }'
property stack
stack: string;
method showSourceCode
showSourceCode: (color?: boolean) => string;
Returns a few lines of CSS source that caused the error.
If the CSS has an input source map without
sourceContent
, this method will return an empty string.error.showSourceCode() //=> " 4 | }// 5 | a {// > 6 | bad// | ^// 7 | }// 8 | b {"Parameter color
Whether arrow will be colored red by terminal color codes. By default, PostCSS will detect color support by
process.stdout.isTTY
andprocess.env.NODE_DISABLE_COLORS
. Few lines of CSS source that caused the error.
method toString
toString: () => string;
Returns error position, message and source code of the broken part.
error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block// > 1 | a {// | ^"Error position, message and source code.
class Declaration
class Declaration_ extends Node {}
It represents a class that handles [CSS declarations](https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_declarations)
Once (root, { Declaration }) {const color = new Declaration({ prop: 'color', value: 'black' })root.append(color)}const root = postcss.parse('a { color: black }')const decl = root.first?.firstdecl.type //=> 'decl'decl.toString() //=> ' color: black'
constructor
constructor(defaults?: Declaration.DeclarationProps);
property important
important: boolean;
It represents a specificity of the declaration.
If true, the CSS declaration will have an [important](https://developer.mozilla.org/en-US/docs/Web/CSS/important) specifier.
const root = postcss.parse('a { color: black !important; color: red }')root.first.first.important //=> trueroot.first.last.important //=> undefined
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property prop
prop: string;
The property name for a CSS declaration.
const root = postcss.parse('a { color: black }')const decl = root.first.firstdecl.prop //=> 'color'
property raws
raws: Declaration.DeclarationRaws;
property type
type: string;
property value
value: string;
The property value for a CSS declaration.
Any CSS comments inside the value string will be filtered out. CSS comments present in the source value will be available in the
raws
property.Assigning new
value
would ignore the comments inraws
property while compiling node to string.const root = postcss.parse('a { color: black }')const decl = root.first.firstdecl.value //=> 'black'
property variable
readonly variable: boolean;
It represents a getter that returns
true
if a declaration starts with--
or$
, which are used to declare variables in CSS and SASS/SCSS.const root = postcss.parse(':root { --one: 1 }')const one = root.first.firstone.variable //=> trueconst root = postcss.parse('$one: 1')const one = root.firstone.variable //=> true
method assign
assign: (overrides: Declaration.DeclarationProps | object) => this;
method clone
clone: (overrides?: Partial<Declaration.DeclarationProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Declaration.DeclarationProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Declaration.DeclarationProps>) => this;
class Document
class Document_ extends Container<Root> {}
Represents a file and contains all its parsed nodes.
**Experimental:** some aspects of this node could change within minor or patch version releases.
const document = htmlParser('<html><style>a{color:black}</style><style>b{z-index:2}</style>')document.type //=> 'document'document.nodes.length //=> 2
constructor
constructor(defaults?: Document.DocumentProps);
property nodes
nodes: Root[];
property parent
parent: undefined;
property type
type: string;
method assign
assign: (overrides: Document.DocumentProps | object) => this;
method clone
clone: (overrides?: Partial<Document.DocumentProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Document.DocumentProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Document.DocumentProps>) => this;
method toResult
toResult: (options?: ProcessOptions) => Result;
Returns a
Result
instance representing the document’s CSS roots.const root1 = postcss.parse(css1, { from: 'a.css' })const root2 = postcss.parse(css2, { from: 'b.css' })const document = postcss.document()document.append(root1)document.append(root2)const result = document.toResult({ to: 'all.css', map: true })Parameter opts
Options. Result with current document’s CSS.
class Input
class Input_ {}
Represents the source CSS.
const root = postcss.parse(css, { from: file })const input = root.source.input
constructor
constructor(css: string, opts?: ProcessOptions<Document_ | Root_>);
Parameter css
Input CSS source.
Parameter opts
Process options.
property css
css: string;
Input CSS source.
const input = postcss.parse('a{}', { from: file }).inputinput.css //=> "a{}"
property file
file?: string;
The absolute path to the CSS source file defined with the
from
option.const root = postcss.parse(css, { from: 'a.css' })root.source.input.file //=> '/home/ai/a.css'
property from
readonly from: string;
The CSS source identifier. Contains
Input#file
if the user set thefrom
option, orInput#id
if they did not.const root = postcss.parse(css, { from: 'a.css' })root.source.input.from //=> "/home/ai/a.css"const root = postcss.parse(css)root.source.input.from //=> "<input css 1>"
property hasBOM
hasBOM: boolean;
The flag to indicate whether or not the source code has Unicode BOM.
property id
id?: string;
The unique ID of the CSS source. It will be created if
from
option is not provided (because PostCSS does not know the file path).const root = postcss.parse(css)root.source.input.file //=> undefinedroot.source.input.id //=> "<input css 8LZeVF>"
property map
map: PreviousMap;
The input source map passed from a compilation step before PostCSS (for example, from Sass compiler).
root.source.input.map.consumer().sources //=> ['a.sass']
method error
error: { ( message: string, start: { column: number; line: number } | { offset: number }, end: { column: number; line: number } | { offset: number }, opts?: { plugin?: CssSyntaxError['plugin'] } ): CssSyntaxError; ( message: string, line: number, column: number, opts?: { plugin?: string } ): CssSyntaxError; ( message: string, offset: number, opts?: { plugin?: string } ): CssSyntaxError;};
Returns
CssSyntaxError
with information about the error and its position.
method fromOffset
fromOffset: (offset: number) => { col: number; line: number } | null;
Converts source offset to line and column.
Parameter offset
Source offset.
method origin
origin: ( line: number, column: number, endLine?: number, endColumn?: number) => false | Input.FilePosition;
Reads the input source map and returns a symbol position in the input source (e.g., in a Sass file that was compiled to CSS before being passed to PostCSS). Optionally takes an end position, exclusive.
root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }root.source.input.origin(1, 1, 1, 4)//=> { file: 'a.css', line: 3, column: 1, endLine: 3, endColumn: 4 }Parameter line
Line for inclusive start position in input CSS.
Parameter column
Column for inclusive start position in input CSS.
Parameter endLine
Line for exclusive end position in input CSS.
Parameter endColumn
Column for exclusive end position in input CSS.
Position in input source.
method toJSON
toJSON: () => object;
Converts this to a JSON-friendly object representation.
class LazyResult
class LazyResult_<RootNode = Document | Root> implements PromiseLike<Result<RootNode>> {}
A Promise proxy for the result of PostCSS transformations.
A
LazyResult
instance is returned byProcessor#process
.const lazy = postcss([autoprefixer]).process(css)
constructor
constructor(processor: Processor, css: string, opts: ResultOptions);
Parameter processor
Processor used for this transformation.
Parameter css
CSS to parse and transform.
Parameter opts
Options from the
Processor#process
orRoot#toResult
.
property [Symbol.toStringTag]
readonly [Symbol.toStringTag]: string;
Returns the default string description of an object. Required to implement the Promise interface.
property catch
catch: <TResult = never>( onrejected?: (reason: any) => TResult | PromiseLike<TResult>) => Promise<Result<RootNode> | TResult>;
Processes input CSS through synchronous and asynchronous plugins and calls onRejected for each error thrown in any plugin.
It implements standard Promise API.
postcss([autoprefixer]).process(css).then(result => {console.log(result.css)}).catch(error => {console.error(error)})
property content
readonly content: string;
An alias for the
css
property. Use it with syntaxes that generate non-CSS output.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property css
readonly css: string;
Processes input CSS through synchronous plugins, converts
Root
to a CSS string and returnsResult#css
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property finally
finally: (onfinally?: () => void) => Promise<Result<RootNode>>;
Processes input CSS through synchronous and asynchronous plugins and calls onFinally on any error or when all plugins will finish work.
It implements standard Promise API.
postcss([autoprefixer]).process(css).finally(() => {console.log('processing ended')})
property map
readonly map: any;
Processes input CSS through synchronous plugins and returns
Result#map
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property messages
readonly messages: Message[];
Processes input CSS through synchronous plugins and returns
Result#messages
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property opts
readonly opts: ResultOptions;
Options from the
Processor#process
call.
property processor
readonly processor: Processor;
Returns a
Processor
instance, which will be used for CSS transformations.
property root
readonly root: {};
Processes input CSS through synchronous plugins and returns
Result#root
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property then
then: <TResult1 = Result<RootNode>, TResult2 = never>( onfulfilled?: (value: Result<RootNode>) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<TResult1 | TResult2>;
Processes input CSS through synchronous and asynchronous plugins and calls
onFulfilled
with a Result instance. If a plugin throws an error, theonRejected
callback will be executed.It implements standard Promise API.
postcss([autoprefixer]).process(css, { from: cssPath }).then(result => {console.log(result.css)})
method async
async: () => Promise<Result<RootNode>>;
Run plugin in async way and return
Result
.Result with output content.
method sync
sync: () => Result<RootNode>;
Run plugin in sync way and return
Result
.Result with output content.
method toString
toString: () => string;
Alias for the
LazyResult#css
property.lazy + '' === lazy.cssOutput CSS.
method warnings
warnings: () => Warning[];
Processes input CSS through synchronous plugins and calls
Result#warnings
.Warnings from plugins.
class Node
class Node extends Node_ {}
class Processor
class Processor_ {}
Contains plugins to process CSS. Create one
Processor
instance, initialize its plugins, and then use that instance on numerous CSS files.const processor = postcss([autoprefixer, postcssNested])processor.process(css1).then(result => console.log(result.css))processor.process(css2).then(result => console.log(result.css))
constructor
constructor(plugins?: readonly AcceptedPlugin[]);
Parameter plugins
PostCSS plugins
property plugins
plugins: (Plugin | TransformCallback | Transformer)[];
Plugins added to this processor.
const processor = postcss([autoprefixer, postcssNested])processor.plugins.length //=> 2
property version
version: string;
Current PostCSS version.
if (result.processor.version.split('.')[0] !== '6') {throw new Error('This plugin works only with PostCSS 6')}
method process
process: { (css: { toString(): string } | LazyResult | Result | Root | string): | LazyResult | NoWorkResult; <RootNode extends Document | Root = Root>( css: | string | Root | Result<Document | Root> | LazyResult<Document | Root> | { toString(): string }, options: ProcessOptions<RootNode> ): LazyResult<RootNode>;};
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 theLazyResult
methods.processor.process(css, { from: 'a.css', to: 'a.out.css' }).then(result => {console.log(result.css)})Parameter css
String with input CSS or any object with a
toString()
method, like a Buffer. Optionally, send aResult
instance and the processor will take theRoot
from it.Parameter opts
Options. Promise proxy.
method use
use: (plugin: AcceptedPlugin) => this;
Adds a plugin to be used as a CSS processor.
PostCSS plugin can be in 4 formats: * A plugin in
Plugin
format. * A plugin creator function withpluginCreator.postcss = true
. PostCSS will call this function without argument to get plugin. * A function. PostCSS will pass the function a Root as the first argument and currentResult
instance as the second. * AnotherProcessor
instance. PostCSS will copy plugins from that instance into this one.Plugins can also be added by passing them as arguments when creating a
postcss
instance (see [postcss(plugins)
]).Asynchronous plugins should return a
Promise
instance.const processor = postcss().use(autoprefixer).use(postcssNested)Parameter plugin
PostCSS plugin or
Processor
with plugins. Current processor to make methods chain.
class Result
class Result_<RootNode = Document | Root> {}
Provides the result of the PostCSS transformations.
A Result instance is returned by
LazyResult#then
orRoot#toResult
methods.postcss([autoprefixer]).process(css).then(result => {console.log(result.css)})const result2 = postcss.parse(css).toResult()
constructor
constructor(processor: Processor, root: {}, opts: Result.ResultOptions);
Parameter processor
Processor used for this transformation.
Parameter root
Root node after all transformations.
Parameter opts
Options from the
Processor#process
orRoot#toResult
.
property content
readonly content: string;
An alias for the
Result#css
property. Use it with syntaxes that generate non-CSS output.result.css === result.content
property css
css: string;
A CSS string representing of
Result#root
.postcss.parse('a{}').toResult().css //=> "a{}"
property lastPlugin
lastPlugin: Plugin | TransformCallback;
Last runned PostCSS plugin.
property map
map: any;
An instance of
SourceMapGenerator
class from thesource-map
library, representing changes to theResult#root
instance.result.map.toJSON() //=> { version: 3, file: 'a.css', … }if (result.map) {fs.writeFileSync(result.opts.to + '.map', result.map.toString())}
property messages
messages: Result.Message[];
Contains messages from plugins (e.g., warnings or custom messages). Each message should have type and plugin properties.
AtRule: {import: (atRule, { result }) {const importedFile = parseImport(atRule)result.messages.push({type: 'dependency',plugin: 'postcss-import',file: importedFile,parent: result.opts.from})}}
property opts
opts: Result.ResultOptions;
Options from the
Processor#process
orRoot#toResult
call that produced this Result instance.]root.toResult(opts).opts === opts
property processor
processor: Processor;
The Processor instance used for this transformation.
for (const plugin of result.processor.plugins) {if (plugin.postcssPlugin === 'postcss-bad') {throw 'postcss-good is incompatible with postcss-bad'}})
property root
root: {};
Root node after all transformations.
root.toResult().root === root
method toString
toString: () => string;
Returns for
Result#css
content.result + '' === result.cssString representing of
Result#root
.
method warn
warn: (message: string, options?: WarningOptions) => Warning;
Creates an instance of
Warning
and adds it toResult#messages
.if (decl.important) {result.warn('Avoid !important', { node: decl, word: '!important' })}Parameter text
Warning message.
Parameter opts
Warning options. Created warning.
method warnings
warnings: () => Warning[];
Returns warnings from plugins. Filters
Warning
instances fromResult#messages
.result.warnings().forEach(warn => {console.warn(warn.toString())})Warnings from plugins.
class Root
class Root_ extends Container {}
Represents a CSS file and contains all its parsed nodes.
const root = postcss.parse('a{color:black} b{z-index:2}')root.type //=> 'root'root.nodes.length //=> 2
constructor
constructor(defaults?: Root.RootProps);
property nodes
nodes: Node.ChildNode[];
property parent
parent: Document;
property raws
raws: Root.RootRaws;
property type
type: string;
method assign
assign: (overrides: object | Root.RootProps) => this;
method clone
clone: (overrides?: Partial<Root.RootProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Root.RootProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Root.RootProps>) => this;
method toResult
toResult: (options?: ProcessOptions) => Result;
Returns a
Result
instance representing the root’s CSS.const root1 = postcss.parse(css1, { from: 'a.css' })const root2 = postcss.parse(css2, { from: 'b.css' })root1.append(root2)const result = root1.toResult({ to: 'all.css', map: true })Parameter options
Options. Result with current root’s CSS.
class Rule
class Rule_ extends Container {}
Represents a CSS rule: a selector followed by a declaration block.
Once (root, { Rule }) {let a = new Rule({ selector: 'a' })a.append(…)root.append(a)}const root = postcss.parse('a{}')const rule = root.firstrule.type //=> 'rule'rule.toString() //=> 'a{}'
constructor
constructor(defaults?: Rule.RuleProps);
property nodes
nodes: Node.ChildNode[];
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property raws
raws: Rule.RuleRaws;
property selector
selector: string;
The rule’s full selector represented as a string.
const root = postcss.parse('a, b { }')const rule = root.firstrule.selector //=> 'a, b'
property selectors
selectors: string[];
An array containing the rule’s individual selectors. Groups of selectors are split at commas.
const root = postcss.parse('a, b { }')const rule = root.firstrule.selector //=> 'a, b'rule.selectors //=> ['a', 'b']rule.selectors = ['a', 'strong']rule.selector //=> 'a, strong'
property type
type: string;
method assign
assign: (overrides: object | Rule.RuleProps) => this;
method clone
clone: (overrides?: Partial<Rule.RuleProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Rule.RuleProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Rule.RuleProps>) => this;
class Warning
class Warning_ {}
Represents a plugin’s warning. It can be created using
Node#warn
.if (decl.important) {decl.warn(result, 'Avoid !important', { word: '!important' })}
constructor
constructor(text: string, opts?: Warning.WarningOptions);
Parameter text
Warning message.
Parameter opts
Warning options.
property column
column: number;
Column for inclusive start position in the input file with this warning’s source.
warning.column //=> 6
property endColumn
endColumn?: number;
Column for exclusive end position in the input file with this warning’s source.
warning.endColumn //=> 4
property endLine
endLine?: number;
Line for exclusive end position in the input file with this warning’s source.
warning.endLine //=> 6
property line
line: number;
Line for inclusive start position in the input file with this warning’s source.
warning.line //=> 5
property node
node: Node;
Contains the CSS node that caused the warning.
warning.node.toString() //=> 'color: white !important'
property plugin
plugin: string;
The name of the plugin that created this warning. When you call
Node#warn
it will fill this property automatically.warning.plugin //=> 'postcss-important'
property text
text: string;
The warning message.
warning.text //=> 'Try to avoid !important'
property type
type: string;
Type to filter warnings from
Result#messages
. Always equal to"warning"
.
method toString
toString: () => string;
Returns a warning position and message.
warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'Warning position and message.
interface AtRuleProps
interface AtRuleProps extends ContainerProps {}
interface Builder
interface Builder {}
call signature
(part: string, node?: AnyNode, type?: 'end' | 'start'): void;
interface CommentProps
interface CommentProps extends NodeProps {}
interface ContainerProps
interface ContainerProps extends NodeProps {}
property nodes
nodes?: readonly (ChildProps | Node)[];
interface DeclarationProps
interface DeclarationProps {}
property important
important?: boolean;
Whether the declaration has an
!important
annotation.
property prop
prop: string;
Name of the declaration.
property raws
raws?: DeclarationRaws;
Information used to generate byte-to-byte equal node string as it was in the origin input.
property value
value: string;
Value of the declaration.
interface DocumentProps
interface DocumentProps extends ContainerProps {}
interface FilePosition
interface FilePosition {}
property column
column: number;
Column of inclusive start position in source file.
property endColumn
endColumn?: number;
Column of exclusive end position in source file.
property endLine
endLine?: number;
Line of exclusive end position in source file.
property file
file?: string;
Absolute path to the source file.
property line
line: number;
Line of inclusive start position in source file.
property source
source?: string;
Source code.
property url
url: string;
URL for the source file.
interface JSONHydrator
interface JSONHydrator {}
call signature
(data: object): Node;
call signature
(data: object[]): Node[];
interface Message
interface Message {}
property plugin
plugin?: string;
Source PostCSS plugin name.
property type
type: string;
Message type.
index signature
[others: string]: any;
interface NodeErrorOptions
interface NodeErrorOptions {}
property endIndex
endIndex?: number;
An ending index inside a node's string that should be highlighted as source of error.
property index
index?: number;
An index inside a node's string that should be highlighted as source of error.
property plugin
plugin?: string;
Plugin name that created this error. PostCSS will set it automatically.
property word
word?: string;
A word inside a node's string, that should be highlighted as source of error.
interface NodeProps
interface NodeProps {}
Interface represents an interface for an object received as parameter by Node class constructor.
property source
source?: Source;
interface OldPlugin
interface OldPlugin<T> extends Transformer {}
property postcss
postcss: Transformer;
call signature
(opts?: T): Transformer;
interface Parser
interface Parser<RootNode = Document | Root> {}
call signature
( css: { toString(): string } | string, opts?: Pick<ProcessOptions, 'from' | 'map'>): RootNode;
interface Plugin
interface Plugin extends Processors {}
property postcssPlugin
postcssPlugin: string;
property prepare
prepare?: (result: Result) => Processors;
interface PluginCreator
interface PluginCreator<PluginOptions> {}
property postcss
postcss: true;
call signature
(opts?: PluginOptions): Plugin | Processor;
interface Position
interface Position {}
interface ProcessOptions
interface ProcessOptions<RootNode = Document | Root> {}
property from
from?: string | undefined;
The path of the CSS source file. You should always set
from
, because it is used in source map generation and syntax error messages.
property map
map?: boolean | SourceMapOptions;
Source map options
property parser
parser?: Parser<RootNode> | Syntax<RootNode>;
Function to generate AST by string.
property stringifier
stringifier?: Stringifier | Syntax<RootNode>;
Class to generate string by AST.
property syntax
syntax?: Syntax<RootNode>;
Object with parse and stringify.
property to
to?: string;
The path where you'll put the output CSS file. You should always set
to
to generate correct source maps.
interface RootProps
interface RootProps extends ContainerProps {}
property raws
raws?: RootRaws;
Information used to generate byte-to-byte equal node string as it was in the origin input.
interface Source
interface Source {}
Source represents an interface for the Node.source property.
interface SourceMapOptions
interface SourceMapOptions {}
property absolute
absolute?: boolean;
Use absolute path in generated source map.
property annotation
annotation?: ((file: string, root: Root) => string) | boolean | string;
Indicates that PostCSS should add annotation comments to the CSS. By default, PostCSS will always add a comment with a path to the source map. PostCSS will not add annotations to CSS files that do not contain any comments.
By default, PostCSS presumes that you want to save the source map as
opts.to + '.map'
and will use this path in the annotation comment. A different path can be set by providing a string value for annotation.If you have set
inline: true
, annotation cannot be disabled.
property from
from?: string;
Override
from
in map’s sources.
property inline
inline?: boolean;
Indicates that the source map should be embedded in the output CSS as a Base64-encoded comment. By default, it is
true
. But if all previous maps are external, not inline, PostCSS will not embed the map even if you do not set this option.If you have an inline source map, the result.map property will be empty, as the source map will be contained within the text of
result.css
.
property prev
prev?: ((file: string) => string) | boolean | object | string;
Source map content from a previous processing step (e.g., Sass).
PostCSS will try to read the previous source map automatically (based on comments within the source CSS), but you can use this option to identify it manually.
If desired, you can omit the previous map with prev:
false
.
property sourcesContent
sourcesContent?: boolean;
Indicates that PostCSS should set the origin content (e.g., Sass source) of the source map. By default, it is true. But if all previous maps do not contain sources content, PostCSS will also leave it out even if you do not set this option.
interface Stringifier
interface Stringifier {}
call signature
(node: AnyNode, builder: Builder): void;
interface Syntax
interface Syntax<RootNode = Document | Root> {}
interface TransformCallback
interface TransformCallback {}
call signature
(root: Root, result: Result): Promise<void> | void;
interface Transformer
interface Transformer extends TransformCallback {}
property postcssPlugin
postcssPlugin: string;
property postcssVersion
postcssVersion: string;
interface WarningOptions
interface WarningOptions {}
property end
end?: RangePosition;
End position, exclusive, in CSS node string that caused the warning.
property endIndex
endIndex?: number;
End index, exclusive, in CSS node string that caused the warning.
property index
index?: number;
Start index, inclusive, in CSS node string that caused the warning.
property node
node?: Node;
CSS node that caused the warning.
property plugin
plugin?: string;
Name of the plugin that created this warning.
Result#warn
fills this property automatically.
property start
start?: RangePosition;
Start position, inclusive, in CSS node string that caused the warning.
property word
word?: string;
Word in CSS source that caused the warning.
type AcceptedPlugin
type AcceptedPlugin = | { postcss: Processor | TransformCallback; } | OldPlugin<any> | Plugin | PluginCreator<any> | Processor | TransformCallback;
type AnyNode
type AnyNode = AtRule.default | Comment | Declaration | Document | Root | Rule;
type ChildNode
type ChildNode = AtRule.default | Comment | Declaration | Rule;
type ChildProps
type ChildProps = AtRuleProps | CommentProps | DeclarationProps | RuleProps;
type Helpers
type Helpers = { postcss: Postcss; result: Result } & Postcss;
type NewChild
type NewChild = | ChildProps | Node | readonly ChildProps[] | readonly Node[] | readonly string[] | string | undefined;
All types that can be passed into container methods to create or add a new child node.
type Postcss
type Postcss = typeof postcss;
type RuleProps
type RuleProps = { /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ raws?: RuleRaws;} & ( | { /** Selector or selectors of the rule. */ selector: string; selectors?: never; } | { selector?: never; /** Selectors of the rule represented as an array of strings. */ selectors: readonly string[]; }) & ContainerProps;
type SourceMap
type SourceMap = { toJSON(): RawSourceMap;} & SourceMapGenerator;
namespace postcss.postcss.postcss
namespace postcss.postcss.postcss {}
variable fromJSON
let fromJSON: JSONHydrator;
Rehydrate a JSON AST (from
Node#toJSON
) back into the AST classes.const json = root.toJSON()// save to file, send by network, etcconst root2 = postcss.fromJSON(json)
variable parse
let parse: Parser<Root>;
Parses source css and returns a new
Root
orDocument
node, which contains the source CSS nodes.// Simple CSS concatenation with source map supportconst root1 = postcss.parse(css1, { from: file1 })const root2 = postcss.parse(css2, { from: file2 })root1.append(root2).toResult().css
variable stringify
let stringify: Stringifier;
Default function to convert a node tree into a CSS string.
function atRule
atRule: (defaults?: AtRuleProps) => AtRule;
Creates a new
AtRule
node.Parameter defaults
Properties for the new node. New at-rule node.
function comment
comment: (defaults?: CommentProps) => Comment;
Creates a new
Comment
node.Parameter defaults
Properties for the new node. New comment node
function decl
decl: (defaults?: DeclarationProps) => Declaration;
Creates a new
Declaration
node.Parameter defaults
Properties for the new node. New declaration node.
function document
document: (defaults?: DocumentProps) => Document;
Creates a new
Document
node.Parameter defaults
Properties for the new node. New document node.
function postcss
postcss: typeof postcss;
Create a new
Processor
instance that will applyplugins
as CSS processors.let postcss = require('postcss')postcss(plugins).process(css, { from, to }).then(result => {console.log(result.css)})Parameter plugins
PostCSS plugins. Processor to process multiple CSS.
function root
root: (defaults?: RootProps) => Root;
Creates a new
Root
node.Parameter defaults
Properties for the new node. New root node.
function rule
rule: (defaults?: RuleProps) => Rule;
Creates a new
Rule
node.Parameter default
Properties for the new node. New rule node.
class AtRule
class AtRule_ extends Container {}
Represents an at-rule.
Once (root, { AtRule }) {let media = new AtRule({ name: 'media', params: 'print' })media.append(…)root.append(media)}If it’s followed in the CSS by a
{}
block, this node will have a nodes property representing its children.const root = postcss.parse('@charset "UTF-8"; @media print {}')const charset = root.firstcharset.type //=> 'atrule'charset.nodes //=> undefinedconst media = root.lastmedia.nodes //=> []
constructor
constructor(defaults?: AtRule.AtRuleProps);
property name
name: string;
The at-rule’s name immediately follows the
@
.const root = postcss.parse('@media print {}')const media = root.firstmedia.name //=> 'media'
property nodes
nodes: Node.ChildNode[];
An array containing the layer’s children.
const root = postcss.parse('@layer example { a { color: black } }')const layer = root.firstlayer.nodes.length //=> 1layer.nodes[0].selector //=> 'a'Can be
undefinded
if the at-rule has no body.const root = postcss.parse('@layer a, b, c;')const layer = root.firstlayer.nodes //=> undefined
property params
params: string;
The at-rule’s parameters, the values that follow the at-rule’s name but precede any
{}
block.const root = postcss.parse('@media print, screen {}')const media = root.firstmedia.params //=> 'print, screen'
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property raws
raws: AtRule.AtRuleRaws;
property type
type: string;
method assign
assign: (overrides: AtRule.AtRuleProps | object) => this;
method clone
clone: (overrides?: Partial<AtRule.AtRuleProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<AtRule.AtRuleProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<AtRule.AtRuleProps>) => this;
class Comment
class Comment_ extends Node {}
It represents a class that handles [CSS comments](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments)
Once (root, { Comment }) {const note = new Comment({ text: 'Note: …' })root.append(note)}Remember that CSS comments inside selectors, at-rule parameters, or declaration values will be stored in the
raws
properties explained above.
constructor
constructor(defaults?: Comment.CommentProps);
property parent
parent: Container<Node.ChildNode>;
property raws
raws: Comment.CommentRaws;
property text
text: string;
The comment's text.
property type
type: string;
method assign
assign: (overrides: Comment.CommentProps | object) => this;
method clone
clone: (overrides?: Partial<Comment.CommentProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Comment.CommentProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Comment.CommentProps>) => this;
class Container
abstract class Container_<Child extends Node = ChildNode> extends Node {}
The
Root
,AtRule
, andRule
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.
property first
readonly first: Node;
The container’s first child.
rule.first === rules.nodes[0]
property last
readonly last: Node;
The container’s last child.
rule.last === rule.nodes[rule.nodes.length - 1]
property nodes
nodes: Child[];
An array containing the container’s children.
const root = postcss.parse('a { color: black }')root.nodes.length //=> 1root.nodes[0].selector //=> 'a'root.nodes[0].nodes[0].prop //=> 'color'
method append
append: (...nodes: Container.NewChild[]) => this;
Inserts new nodes to the end of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })const decl2 = new Declaration({ prop: 'background-color', value: 'white' })rule.append(decl1, decl2)root.append({ name: 'charset', params: '"UTF-8"' }) // at-ruleroot.append({ selector: 'a' }) // rulerule.append({ prop: 'color', value: 'black' }) // declarationrule.append({ text: 'Comment' }) // commentroot.append('a {}')root.first.append('color: black; z-index: 1')Parameter nodes
New nodes. This node for methods chain.
method assign
assign: (overrides: Container.ContainerProps | object) => this;
method clone
clone: (overrides?: Partial<Container.ContainerProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Container.ContainerProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Container.ContainerProps>) => this;
method each
each: ( callback: (node: Child, index: number) => false | void) => false | undefined;
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 orArray#forEach
this iterator is safe if you are mutating the array of child nodes during iteration. PostCSS will adjust the current index to match the mutations.const root = postcss.parse('a { color: black; z-index: 1 }')const rule = root.firstfor (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})Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method every
every: ( condition: (node: Child, index: number, nodes: Child[]) => boolean) => boolean;
Returns
true
if callback returnstrue
for all of the container’s children.const noPrefixes = rule.every(i => i.prop[0] !== '-')Parameter condition
Iterator returns true or false. Is every child pass condition.
method index
index: (child: Child | number) => number;
Returns a
child
’s index within theContainer#nodes
array.rule.index( rule.nodes[2] ) //=> 2Parameter child
Child of the current container. Child index.
method insertAfter
insertAfter: (oldNode: Child | number, newNode: Container.NewChild) => this;
Insert new node after old node within the container.
Parameter oldNode
Child or child’s index.
Parameter newNode
New node. This node for methods chain.
method insertBefore
insertBefore: (oldNode: Child | number, newNode: Container.NewChild) => this;
Insert new node before old node within the container.
rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))Parameter oldNode
Child or child’s index.
Parameter newNode
New node. This node for methods chain.
method normalize
protected normalize: ( nodes: Container.NewChild, sample: Node | undefined, type?: 'prepend' | false) => Child[];
An internal method that converts a NewChild into a list of actual child nodes that can then be added to this container.
This ensures that the nodes' parent is set to this container, that they use the correct prototype chain, and that they're marked as dirty.
Parameter mnodes
The new node or nodes to add.
Parameter sample
A node from whose raws the new node's
before
raw should be taken.Parameter type
This should be set to
'prepend'
if the new nodes will be inserted at the beginning of the container.
method prepend
prepend: (...nodes: Container.NewChild[]) => this;
Inserts new nodes to the start of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })const decl2 = new Declaration({ prop: 'background-color', value: 'white' })rule.prepend(decl1, decl2)root.append({ name: 'charset', params: '"UTF-8"' }) // at-ruleroot.append({ selector: 'a' }) // rulerule.append({ prop: 'color', value: 'black' }) // declarationrule.append({ text: 'Comment' }) // commentroot.append('a {}')root.first.append('color: black; z-index: 1')Parameter nodes
New nodes. This node for methods chain.
method push
push: (child: Child) => this;
Add child to the end of the node.
rule.push(new Declaration({ prop: 'color', value: 'black' }))Parameter child
New node. This node for methods chain.
method removeAll
removeAll: () => this;
Removes all children from the container and cleans their parent properties.
rule.removeAll()rule.nodes.length //=> 0This node for methods chain.
method removeChild
removeChild: (child: Child | number) => this;
Removes node from the container and cleans the parent properties from the node and its children.
rule.nodes.length //=> 5rule.removeChild(decl)rule.nodes.length //=> 4decl.parent //=> undefinedParameter child
Child or child’s index. This node for methods chain.
method replaceValues
replaceValues: { ( pattern: RegExp | string, replaced: string | ((substring: string, ...args: any[]) => string) ): this; ( pattern: string | RegExp, options: Container.ValueOptions, replaced: string | ((substring: string, ...args: any[]) => string) ): this;};
Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.
This method is useful if you are using a custom unit or function and need to iterate through all values.
root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {return 15 * parseInt(string) + 'px'})Parameter pattern
Replace pattern.
Parameter options
Options to speed up the search.
Parameter replaced
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
. This node for methods chain.
method some
some: ( condition: (node: Child, index: number, nodes: Child[]) => boolean) => boolean;
Returns
true
if callback returnstrue
for (at least) one of the container’s children.const hasPrefix = rule.some(i => i.prop[0] === '-')Parameter condition
Iterator returns true or false. Is some child pass condition.
method walk
walk: ( callback: (node: ChildNode, index: number) => false | void) => false | undefined;
Traverses the container’s descendant nodes, calling callback for each node.
Like container.each(), this method is safe to use if you are mutating arrays during iteration.
If you only need to iterate through the container’s immediate children, use
Container#each
.root.walk(node => {// Traverses all descendant nodes.})Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkAtRules
walkAtRules: { ( nameFilter: RegExp | string, callback: (atRule: AtRule, index: number) => false | void ): false | undefined; (callback: (atRule: AtRule, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each at-rule node.
If you pass a filter, iteration will only happen over at-rules that have matching names.
Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.root.walkAtRules(rule => {if (isOld(rule.name)) rule.remove()})let first = falseroot.walkAtRules('charset', rule => {if (!first) {first = true} else {rule.remove()}})Parameter name
String or regular expression to filter at-rules by name.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkComments
walkComments: { (callback: (comment: Comment, indexed: number) => false | void): | false | undefined; (callback: (comment: Comment, indexed: number) => false | void): false;};
method walkDecls
walkDecls: { ( propFilter: RegExp | string, callback: (decl: Declaration, index: number) => false | void ): false | undefined; (callback: (decl: Declaration, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each declaration node.
If you pass a filter, iteration will only happen over declarations with matching properties.
root.walkDecls(decl => {checkPropertySupport(decl.prop)})root.walkDecls('border-radius', decl => {decl.remove()})root.walkDecls(/^background/, decl => {decl.value = takeFirstColorFromGradient(decl.value)})Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.Parameter prop
String or regular expression to filter declarations by property name.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkRules
walkRules: { ( selectorFilter: RegExp | string, callback: (rule: Rule, index: number) => false | void ): false | undefined; (callback: (rule: Rule, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each rule node.
If you pass a filter, iteration will only happen over rules with matching selectors.
Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.const selectors = []root.walkRules(rule => {selectors.push(rule.selector)})console.log(`Your CSS uses ${ selectors.length } selectors`)Parameter selector
String or regular expression to filter rules by selector.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
class CssSyntaxError
class CssSyntaxError_ extends Error {}
The CSS parser throws this error for broken CSS.
Custom parsers can throw this error for broken custom syntax using the
Node#error
method.PostCSS will use the input source map to detect the original error location. If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS, PostCSS will show the original position in the Sass file.
If you need the position in the PostCSS input (e.g., to debug the previous compiler), use
error.input.file
.// Raising error from pluginthrow node.error('Unknown variable', { plugin: 'postcss-vars' })// Catching and checking syntax errortry {postcss.parse('a{')} catch (error) {if (error.name === 'CssSyntaxError') {error //=> CssSyntaxError}}
constructor
constructor( message: string, lineOrStartPos?: number | CssSyntaxError.RangePosition, columnOrEndPos?: number | CssSyntaxError.RangePosition, source?: string, file?: string, plugin?: string);
Instantiates a CSS syntax error. Can be instantiated for a single position or for a range.
Parameter message
Error message.
Parameter lineOrStartPos
If for a single position, the line number, or if for a range, the inclusive start position of the error.
Parameter columnOrEndPos
If for a single position, the column number, or if for a range, the exclusive end position of the error.
Parameter source
Source code of the broken file.
Parameter file
Absolute path to the broken file.
Parameter plugin
PostCSS plugin name, if error came from plugin.
property column
column?: number;
Source column of the error.
error.column //=> 1error.input.column //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.column
.
property endColumn
endColumn?: number;
Source column of the error's end, exclusive. Provided if the error pertains to a range.
error.endColumn //=> 1error.input.endColumn //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.endColumn
.
property endLine
endLine?: number;
Source line of the error's end, exclusive. Provided if the error pertains to a range.
error.endLine //=> 3error.input.endLine //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.endLine
.
property file
file?: string;
Absolute path to the broken file.
error.file //=> 'a.sass'error.input.file //=> 'a.css'PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.file
.
property input
input?: FilePosition;
Input object with PostCSS internal information about input file. If input has source map from previous tool, PostCSS will use origin (for example, Sass) source. You can use this object to get PostCSS input source.
error.input.file //=> 'a.css'error.file //=> 'a.sass'
property line
line?: number;
Source line of the error.
error.line //=> 2error.input.line //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.line
.
property message
message: string;
Full error text in the GNU error format with plugin, file, line and column.
error.message //=> 'a.css:1:1: Unclosed block'
property name
name: string;
Always equal to
'CssSyntaxError'
. You should always check error type byerror.name === 'CssSyntaxError'
instead oferror instanceof CssSyntaxError
, because npm could have several PostCSS versions.if (error.name === 'CssSyntaxError') {error //=> CssSyntaxError}
property plugin
plugin?: string;
Plugin name, if error came from plugin.
error.plugin //=> 'postcss-vars'
property reason
reason: string;
Error message.
error.message //=> 'Unclosed block'
property source
source?: string;
Source code of the broken file.
error.source //=> 'a { b {} }'error.input.source //=> 'a b { }'
property stack
stack: string;
method showSourceCode
showSourceCode: (color?: boolean) => string;
Returns a few lines of CSS source that caused the error.
If the CSS has an input source map without
sourceContent
, this method will return an empty string.error.showSourceCode() //=> " 4 | }// 5 | a {// > 6 | bad// | ^// 7 | }// 8 | b {"Parameter color
Whether arrow will be colored red by terminal color codes. By default, PostCSS will detect color support by
process.stdout.isTTY
andprocess.env.NODE_DISABLE_COLORS
. Few lines of CSS source that caused the error.
method toString
toString: () => string;
Returns error position, message and source code of the broken part.
error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block// > 1 | a {// | ^"Error position, message and source code.
class Declaration
class Declaration_ extends Node {}
It represents a class that handles [CSS declarations](https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_declarations)
Once (root, { Declaration }) {const color = new Declaration({ prop: 'color', value: 'black' })root.append(color)}const root = postcss.parse('a { color: black }')const decl = root.first?.firstdecl.type //=> 'decl'decl.toString() //=> ' color: black'
constructor
constructor(defaults?: Declaration.DeclarationProps);
property important
important: boolean;
It represents a specificity of the declaration.
If true, the CSS declaration will have an [important](https://developer.mozilla.org/en-US/docs/Web/CSS/important) specifier.
const root = postcss.parse('a { color: black !important; color: red }')root.first.first.important //=> trueroot.first.last.important //=> undefined
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property prop
prop: string;
The property name for a CSS declaration.
const root = postcss.parse('a { color: black }')const decl = root.first.firstdecl.prop //=> 'color'
property raws
raws: Declaration.DeclarationRaws;
property type
type: string;
property value
value: string;
The property value for a CSS declaration.
Any CSS comments inside the value string will be filtered out. CSS comments present in the source value will be available in the
raws
property.Assigning new
value
would ignore the comments inraws
property while compiling node to string.const root = postcss.parse('a { color: black }')const decl = root.first.firstdecl.value //=> 'black'
property variable
readonly variable: boolean;
It represents a getter that returns
true
if a declaration starts with--
or$
, which are used to declare variables in CSS and SASS/SCSS.const root = postcss.parse(':root { --one: 1 }')const one = root.first.firstone.variable //=> trueconst root = postcss.parse('$one: 1')const one = root.firstone.variable //=> true
method assign
assign: (overrides: Declaration.DeclarationProps | object) => this;
method clone
clone: (overrides?: Partial<Declaration.DeclarationProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Declaration.DeclarationProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Declaration.DeclarationProps>) => this;
class Document
class Document_ extends Container<Root> {}
Represents a file and contains all its parsed nodes.
**Experimental:** some aspects of this node could change within minor or patch version releases.
const document = htmlParser('<html><style>a{color:black}</style><style>b{z-index:2}</style>')document.type //=> 'document'document.nodes.length //=> 2
constructor
constructor(defaults?: Document.DocumentProps);
property nodes
nodes: Root[];
property parent
parent: undefined;
property type
type: string;
method assign
assign: (overrides: Document.DocumentProps | object) => this;
method clone
clone: (overrides?: Partial<Document.DocumentProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Document.DocumentProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Document.DocumentProps>) => this;
method toResult
toResult: (options?: ProcessOptions) => Result;
Returns a
Result
instance representing the document’s CSS roots.const root1 = postcss.parse(css1, { from: 'a.css' })const root2 = postcss.parse(css2, { from: 'b.css' })const document = postcss.document()document.append(root1)document.append(root2)const result = document.toResult({ to: 'all.css', map: true })Parameter opts
Options. Result with current document’s CSS.
class Input
class Input_ {}
Represents the source CSS.
const root = postcss.parse(css, { from: file })const input = root.source.input
constructor
constructor(css: string, opts?: ProcessOptions<Document_ | Root_>);
Parameter css
Input CSS source.
Parameter opts
Process options.
property css
css: string;
Input CSS source.
const input = postcss.parse('a{}', { from: file }).inputinput.css //=> "a{}"
property file
file?: string;
The absolute path to the CSS source file defined with the
from
option.const root = postcss.parse(css, { from: 'a.css' })root.source.input.file //=> '/home/ai/a.css'
property from
readonly from: string;
The CSS source identifier. Contains
Input#file
if the user set thefrom
option, orInput#id
if they did not.const root = postcss.parse(css, { from: 'a.css' })root.source.input.from //=> "/home/ai/a.css"const root = postcss.parse(css)root.source.input.from //=> "<input css 1>"
property hasBOM
hasBOM: boolean;
The flag to indicate whether or not the source code has Unicode BOM.
property id
id?: string;
The unique ID of the CSS source. It will be created if
from
option is not provided (because PostCSS does not know the file path).const root = postcss.parse(css)root.source.input.file //=> undefinedroot.source.input.id //=> "<input css 8LZeVF>"
property map
map: PreviousMap;
The input source map passed from a compilation step before PostCSS (for example, from Sass compiler).
root.source.input.map.consumer().sources //=> ['a.sass']
method error
error: { ( message: string, start: { column: number; line: number } | { offset: number }, end: { column: number; line: number } | { offset: number }, opts?: { plugin?: CssSyntaxError['plugin'] } ): CssSyntaxError; ( message: string, line: number, column: number, opts?: { plugin?: string } ): CssSyntaxError; ( message: string, offset: number, opts?: { plugin?: string } ): CssSyntaxError;};
Returns
CssSyntaxError
with information about the error and its position.
method fromOffset
fromOffset: (offset: number) => { col: number; line: number } | null;
Converts source offset to line and column.
Parameter offset
Source offset.
method origin
origin: ( line: number, column: number, endLine?: number, endColumn?: number) => false | Input.FilePosition;
Reads the input source map and returns a symbol position in the input source (e.g., in a Sass file that was compiled to CSS before being passed to PostCSS). Optionally takes an end position, exclusive.
root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }root.source.input.origin(1, 1, 1, 4)//=> { file: 'a.css', line: 3, column: 1, endLine: 3, endColumn: 4 }Parameter line
Line for inclusive start position in input CSS.
Parameter column
Column for inclusive start position in input CSS.
Parameter endLine
Line for exclusive end position in input CSS.
Parameter endColumn
Column for exclusive end position in input CSS.
Position in input source.
method toJSON
toJSON: () => object;
Converts this to a JSON-friendly object representation.
class LazyResult
class LazyResult_<RootNode = Document | Root> implements PromiseLike<Result<RootNode>> {}
A Promise proxy for the result of PostCSS transformations.
A
LazyResult
instance is returned byProcessor#process
.const lazy = postcss([autoprefixer]).process(css)
constructor
constructor(processor: Processor, css: string, opts: ResultOptions);
Parameter processor
Processor used for this transformation.
Parameter css
CSS to parse and transform.
Parameter opts
Options from the
Processor#process
orRoot#toResult
.
property [Symbol.toStringTag]
readonly [Symbol.toStringTag]: string;
Returns the default string description of an object. Required to implement the Promise interface.
property catch
catch: <TResult = never>( onrejected?: (reason: any) => TResult | PromiseLike<TResult>) => Promise<Result<RootNode> | TResult>;
Processes input CSS through synchronous and asynchronous plugins and calls onRejected for each error thrown in any plugin.
It implements standard Promise API.
postcss([autoprefixer]).process(css).then(result => {console.log(result.css)}).catch(error => {console.error(error)})
property content
readonly content: string;
An alias for the
css
property. Use it with syntaxes that generate non-CSS output.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property css
readonly css: string;
Processes input CSS through synchronous plugins, converts
Root
to a CSS string and returnsResult#css
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property finally
finally: (onfinally?: () => void) => Promise<Result<RootNode>>;
Processes input CSS through synchronous and asynchronous plugins and calls onFinally on any error or when all plugins will finish work.
It implements standard Promise API.
postcss([autoprefixer]).process(css).finally(() => {console.log('processing ended')})
property map
readonly map: any;
Processes input CSS through synchronous plugins and returns
Result#map
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property messages
readonly messages: Message[];
Processes input CSS through synchronous plugins and returns
Result#messages
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property opts
readonly opts: ResultOptions;
Options from the
Processor#process
call.
property processor
readonly processor: Processor;
Returns a
Processor
instance, which will be used for CSS transformations.
property root
readonly root: {};
Processes input CSS through synchronous plugins and returns
Result#root
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property then
then: <TResult1 = Result<RootNode>, TResult2 = never>( onfulfilled?: (value: Result<RootNode>) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<TResult1 | TResult2>;
Processes input CSS through synchronous and asynchronous plugins and calls
onFulfilled
with a Result instance. If a plugin throws an error, theonRejected
callback will be executed.It implements standard Promise API.
postcss([autoprefixer]).process(css, { from: cssPath }).then(result => {console.log(result.css)})
method async
async: () => Promise<Result<RootNode>>;
Run plugin in async way and return
Result
.Result with output content.
method sync
sync: () => Result<RootNode>;
Run plugin in sync way and return
Result
.Result with output content.
method toString
toString: () => string;
Alias for the
LazyResult#css
property.lazy + '' === lazy.cssOutput CSS.
method warnings
warnings: () => Warning[];
Processes input CSS through synchronous plugins and calls
Result#warnings
.Warnings from plugins.
class Node
class Node extends Node_ {}
class Processor
class Processor_ {}
Contains plugins to process CSS. Create one
Processor
instance, initialize its plugins, and then use that instance on numerous CSS files.const processor = postcss([autoprefixer, postcssNested])processor.process(css1).then(result => console.log(result.css))processor.process(css2).then(result => console.log(result.css))
constructor
constructor(plugins?: readonly AcceptedPlugin[]);
Parameter plugins
PostCSS plugins
property plugins
plugins: (Plugin | TransformCallback | Transformer)[];
Plugins added to this processor.
const processor = postcss([autoprefixer, postcssNested])processor.plugins.length //=> 2
property version
version: string;
Current PostCSS version.
if (result.processor.version.split('.')[0] !== '6') {throw new Error('This plugin works only with PostCSS 6')}
method process
process: { (css: { toString(): string } | LazyResult | Result | Root | string): | LazyResult | NoWorkResult; <RootNode extends Document | Root = Root>( css: | string | Root | Result<Document | Root> | LazyResult<Document | Root> | { toString(): string }, options: ProcessOptions<RootNode> ): LazyResult<RootNode>;};
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 theLazyResult
methods.processor.process(css, { from: 'a.css', to: 'a.out.css' }).then(result => {console.log(result.css)})Parameter css
String with input CSS or any object with a
toString()
method, like a Buffer. Optionally, send aResult
instance and the processor will take theRoot
from it.Parameter opts
Options. Promise proxy.
method use
use: (plugin: AcceptedPlugin) => this;
Adds a plugin to be used as a CSS processor.
PostCSS plugin can be in 4 formats: * A plugin in
Plugin
format. * A plugin creator function withpluginCreator.postcss = true
. PostCSS will call this function without argument to get plugin. * A function. PostCSS will pass the function a Root as the first argument and currentResult
instance as the second. * AnotherProcessor
instance. PostCSS will copy plugins from that instance into this one.Plugins can also be added by passing them as arguments when creating a
postcss
instance (see [postcss(plugins)
]).Asynchronous plugins should return a
Promise
instance.const processor = postcss().use(autoprefixer).use(postcssNested)Parameter plugin
PostCSS plugin or
Processor
with plugins. Current processor to make methods chain.
class Result
class Result_<RootNode = Document | Root> {}
Provides the result of the PostCSS transformations.
A Result instance is returned by
LazyResult#then
orRoot#toResult
methods.postcss([autoprefixer]).process(css).then(result => {console.log(result.css)})const result2 = postcss.parse(css).toResult()
constructor
constructor(processor: Processor, root: {}, opts: Result.ResultOptions);
Parameter processor
Processor used for this transformation.
Parameter root
Root node after all transformations.
Parameter opts
Options from the
Processor#process
orRoot#toResult
.
property content
readonly content: string;
An alias for the
Result#css
property. Use it with syntaxes that generate non-CSS output.result.css === result.content
property css
css: string;
A CSS string representing of
Result#root
.postcss.parse('a{}').toResult().css //=> "a{}"
property lastPlugin
lastPlugin: Plugin | TransformCallback;
Last runned PostCSS plugin.
property map
map: any;
An instance of
SourceMapGenerator
class from thesource-map
library, representing changes to theResult#root
instance.result.map.toJSON() //=> { version: 3, file: 'a.css', … }if (result.map) {fs.writeFileSync(result.opts.to + '.map', result.map.toString())}
property messages
messages: Result.Message[];
Contains messages from plugins (e.g., warnings or custom messages). Each message should have type and plugin properties.
AtRule: {import: (atRule, { result }) {const importedFile = parseImport(atRule)result.messages.push({type: 'dependency',plugin: 'postcss-import',file: importedFile,parent: result.opts.from})}}
property opts
opts: Result.ResultOptions;
Options from the
Processor#process
orRoot#toResult
call that produced this Result instance.]root.toResult(opts).opts === opts
property processor
processor: Processor;
The Processor instance used for this transformation.
for (const plugin of result.processor.plugins) {if (plugin.postcssPlugin === 'postcss-bad') {throw 'postcss-good is incompatible with postcss-bad'}})
property root
root: {};
Root node after all transformations.
root.toResult().root === root
method toString
toString: () => string;
Returns for
Result#css
content.result + '' === result.cssString representing of
Result#root
.
method warn
warn: (message: string, options?: WarningOptions) => Warning;
Creates an instance of
Warning
and adds it toResult#messages
.if (decl.important) {result.warn('Avoid !important', { node: decl, word: '!important' })}Parameter text
Warning message.
Parameter opts
Warning options. Created warning.
method warnings
warnings: () => Warning[];
Returns warnings from plugins. Filters
Warning
instances fromResult#messages
.result.warnings().forEach(warn => {console.warn(warn.toString())})Warnings from plugins.
class Root
class Root_ extends Container {}
Represents a CSS file and contains all its parsed nodes.
const root = postcss.parse('a{color:black} b{z-index:2}')root.type //=> 'root'root.nodes.length //=> 2
constructor
constructor(defaults?: Root.RootProps);
property nodes
nodes: Node.ChildNode[];
property parent
parent: Document;
property raws
raws: Root.RootRaws;
property type
type: string;
method assign
assign: (overrides: object | Root.RootProps) => this;
method clone
clone: (overrides?: Partial<Root.RootProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Root.RootProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Root.RootProps>) => this;
method toResult
toResult: (options?: ProcessOptions) => Result;
Returns a
Result
instance representing the root’s CSS.const root1 = postcss.parse(css1, { from: 'a.css' })const root2 = postcss.parse(css2, { from: 'b.css' })root1.append(root2)const result = root1.toResult({ to: 'all.css', map: true })Parameter options
Options. Result with current root’s CSS.
class Rule
class Rule_ extends Container {}
Represents a CSS rule: a selector followed by a declaration block.
Once (root, { Rule }) {let a = new Rule({ selector: 'a' })a.append(…)root.append(a)}const root = postcss.parse('a{}')const rule = root.firstrule.type //=> 'rule'rule.toString() //=> 'a{}'
constructor
constructor(defaults?: Rule.RuleProps);
property nodes
nodes: Node.ChildNode[];
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property raws
raws: Rule.RuleRaws;
property selector
selector: string;
The rule’s full selector represented as a string.
const root = postcss.parse('a, b { }')const rule = root.firstrule.selector //=> 'a, b'
property selectors
selectors: string[];
An array containing the rule’s individual selectors. Groups of selectors are split at commas.
const root = postcss.parse('a, b { }')const rule = root.firstrule.selector //=> 'a, b'rule.selectors //=> ['a', 'b']rule.selectors = ['a', 'strong']rule.selector //=> 'a, strong'
property type
type: string;
method assign
assign: (overrides: object | Rule.RuleProps) => this;
method clone
clone: (overrides?: Partial<Rule.RuleProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Rule.RuleProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Rule.RuleProps>) => this;
class Warning
class Warning_ {}
Represents a plugin’s warning. It can be created using
Node#warn
.if (decl.important) {decl.warn(result, 'Avoid !important', { word: '!important' })}
constructor
constructor(text: string, opts?: Warning.WarningOptions);
Parameter text
Warning message.
Parameter opts
Warning options.
property column
column: number;
Column for inclusive start position in the input file with this warning’s source.
warning.column //=> 6
property endColumn
endColumn?: number;
Column for exclusive end position in the input file with this warning’s source.
warning.endColumn //=> 4
property endLine
endLine?: number;
Line for exclusive end position in the input file with this warning’s source.
warning.endLine //=> 6
property line
line: number;
Line for inclusive start position in the input file with this warning’s source.
warning.line //=> 5
property node
node: Node;
Contains the CSS node that caused the warning.
warning.node.toString() //=> 'color: white !important'
property plugin
plugin: string;
The name of the plugin that created this warning. When you call
Node#warn
it will fill this property automatically.warning.plugin //=> 'postcss-important'
property text
text: string;
The warning message.
warning.text //=> 'Try to avoid !important'
property type
type: string;
Type to filter warnings from
Result#messages
. Always equal to"warning"
.
method toString
toString: () => string;
Returns a warning position and message.
warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'Warning position and message.
interface AtRuleProps
interface AtRuleProps extends ContainerProps {}
interface Builder
interface Builder {}
call signature
(part: string, node?: AnyNode, type?: 'end' | 'start'): void;
interface CommentProps
interface CommentProps extends NodeProps {}
interface ContainerProps
interface ContainerProps extends NodeProps {}
property nodes
nodes?: readonly (ChildProps | Node)[];
interface DeclarationProps
interface DeclarationProps {}
property important
important?: boolean;
Whether the declaration has an
!important
annotation.
property prop
prop: string;
Name of the declaration.
property raws
raws?: DeclarationRaws;
Information used to generate byte-to-byte equal node string as it was in the origin input.
property value
value: string;
Value of the declaration.
interface DocumentProps
interface DocumentProps extends ContainerProps {}
interface FilePosition
interface FilePosition {}
property column
column: number;
Column of inclusive start position in source file.
property endColumn
endColumn?: number;
Column of exclusive end position in source file.
property endLine
endLine?: number;
Line of exclusive end position in source file.
property file
file?: string;
Absolute path to the source file.
property line
line: number;
Line of inclusive start position in source file.
property source
source?: string;
Source code.
property url
url: string;
URL for the source file.
interface JSONHydrator
interface JSONHydrator {}
call signature
(data: object): Node;
call signature
(data: object[]): Node[];
interface Message
interface Message {}
property plugin
plugin?: string;
Source PostCSS plugin name.
property type
type: string;
Message type.
index signature
[others: string]: any;
interface NodeErrorOptions
interface NodeErrorOptions {}
property endIndex
endIndex?: number;
An ending index inside a node's string that should be highlighted as source of error.
property index
index?: number;
An index inside a node's string that should be highlighted as source of error.
property plugin
plugin?: string;
Plugin name that created this error. PostCSS will set it automatically.
property word
word?: string;
A word inside a node's string, that should be highlighted as source of error.
interface NodeProps
interface NodeProps {}
Interface represents an interface for an object received as parameter by Node class constructor.
property source
source?: Source;
interface OldPlugin
interface OldPlugin<T> extends Transformer {}
property postcss
postcss: Transformer;
call signature
(opts?: T): Transformer;
interface Parser
interface Parser<RootNode = Document | Root> {}
call signature
( css: { toString(): string } | string, opts?: Pick<ProcessOptions, 'from' | 'map'>): RootNode;
interface Plugin
interface Plugin extends Processors {}
property postcssPlugin
postcssPlugin: string;
property prepare
prepare?: (result: Result) => Processors;
interface PluginCreator
interface PluginCreator<PluginOptions> {}
property postcss
postcss: true;
call signature
(opts?: PluginOptions): Plugin | Processor;
interface Position
interface Position {}
interface ProcessOptions
interface ProcessOptions<RootNode = Document | Root> {}
property from
from?: string | undefined;
The path of the CSS source file. You should always set
from
, because it is used in source map generation and syntax error messages.
property map
map?: boolean | SourceMapOptions;
Source map options
property parser
parser?: Parser<RootNode> | Syntax<RootNode>;
Function to generate AST by string.
property stringifier
stringifier?: Stringifier | Syntax<RootNode>;
Class to generate string by AST.
property syntax
syntax?: Syntax<RootNode>;
Object with parse and stringify.
property to
to?: string;
The path where you'll put the output CSS file. You should always set
to
to generate correct source maps.
interface RootProps
interface RootProps extends ContainerProps {}
property raws
raws?: RootRaws;
Information used to generate byte-to-byte equal node string as it was in the origin input.
interface Source
interface Source {}
Source represents an interface for the Node.source property.
interface SourceMapOptions
interface SourceMapOptions {}
property absolute
absolute?: boolean;
Use absolute path in generated source map.
property annotation
annotation?: ((file: string, root: Root) => string) | boolean | string;
Indicates that PostCSS should add annotation comments to the CSS. By default, PostCSS will always add a comment with a path to the source map. PostCSS will not add annotations to CSS files that do not contain any comments.
By default, PostCSS presumes that you want to save the source map as
opts.to + '.map'
and will use this path in the annotation comment. A different path can be set by providing a string value for annotation.If you have set
inline: true
, annotation cannot be disabled.
property from
from?: string;
Override
from
in map’s sources.
property inline
inline?: boolean;
Indicates that the source map should be embedded in the output CSS as a Base64-encoded comment. By default, it is
true
. But if all previous maps are external, not inline, PostCSS will not embed the map even if you do not set this option.If you have an inline source map, the result.map property will be empty, as the source map will be contained within the text of
result.css
.
property prev
prev?: ((file: string) => string) | boolean | object | string;
Source map content from a previous processing step (e.g., Sass).
PostCSS will try to read the previous source map automatically (based on comments within the source CSS), but you can use this option to identify it manually.
If desired, you can omit the previous map with prev:
false
.
property sourcesContent
sourcesContent?: boolean;
Indicates that PostCSS should set the origin content (e.g., Sass source) of the source map. By default, it is true. But if all previous maps do not contain sources content, PostCSS will also leave it out even if you do not set this option.
interface Stringifier
interface Stringifier {}
call signature
(node: AnyNode, builder: Builder): void;
interface Syntax
interface Syntax<RootNode = Document | Root> {}
interface TransformCallback
interface TransformCallback {}
call signature
(root: Root, result: Result): Promise<void> | void;
interface Transformer
interface Transformer extends TransformCallback {}
property postcssPlugin
postcssPlugin: string;
property postcssVersion
postcssVersion: string;
interface WarningOptions
interface WarningOptions {}
property end
end?: RangePosition;
End position, exclusive, in CSS node string that caused the warning.
property endIndex
endIndex?: number;
End index, exclusive, in CSS node string that caused the warning.
property index
index?: number;
Start index, inclusive, in CSS node string that caused the warning.
property node
node?: Node;
CSS node that caused the warning.
property plugin
plugin?: string;
Name of the plugin that created this warning.
Result#warn
fills this property automatically.
property start
start?: RangePosition;
Start position, inclusive, in CSS node string that caused the warning.
property word
word?: string;
Word in CSS source that caused the warning.
type AcceptedPlugin
type AcceptedPlugin = | { postcss: Processor | TransformCallback; } | OldPlugin<any> | Plugin | PluginCreator<any> | Processor | TransformCallback;
type AnyNode
type AnyNode = AtRule.default | Comment | Declaration | Document | Root | Rule;
type ChildNode
type ChildNode = AtRule.default | Comment | Declaration | Rule;
type ChildProps
type ChildProps = AtRuleProps | CommentProps | DeclarationProps | RuleProps;
type Helpers
type Helpers = { postcss: Postcss; result: Result } & Postcss;
type NewChild
type NewChild = | ChildProps | Node | readonly ChildProps[] | readonly Node[] | readonly string[] | string | undefined;
All types that can be passed into container methods to create or add a new child node.
type Postcss
type Postcss = typeof postcss;
type RuleProps
type RuleProps = { /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ raws?: RuleRaws;} & ( | { /** Selector or selectors of the rule. */ selector: string; selectors?: never; } | { selector?: never; /** Selectors of the rule represented as an array of strings. */ selectors: readonly string[]; }) & ContainerProps;
type SourceMap
type SourceMap = { toJSON(): RawSourceMap;} & SourceMapGenerator;
namespace postcss.postcss.postcss.postcss
namespace postcss.postcss.postcss.postcss {}
variable fromJSON
let fromJSON: JSONHydrator;
Rehydrate a JSON AST (from
Node#toJSON
) back into the AST classes.const json = root.toJSON()// save to file, send by network, etcconst root2 = postcss.fromJSON(json)
variable parse
let parse: Parser<Root>;
Parses source css and returns a new
Root
orDocument
node, which contains the source CSS nodes.// Simple CSS concatenation with source map supportconst root1 = postcss.parse(css1, { from: file1 })const root2 = postcss.parse(css2, { from: file2 })root1.append(root2).toResult().css
variable stringify
let stringify: Stringifier;
Default function to convert a node tree into a CSS string.
function atRule
atRule: (defaults?: AtRuleProps) => AtRule;
Creates a new
AtRule
node.Parameter defaults
Properties for the new node. New at-rule node.
function comment
comment: (defaults?: CommentProps) => Comment;
Creates a new
Comment
node.Parameter defaults
Properties for the new node. New comment node
function decl
decl: (defaults?: DeclarationProps) => Declaration;
Creates a new
Declaration
node.Parameter defaults
Properties for the new node. New declaration node.
function document
document: (defaults?: DocumentProps) => Document;
Creates a new
Document
node.Parameter defaults
Properties for the new node. New document node.
function postcss
postcss: typeof postcss;
Create a new
Processor
instance that will applyplugins
as CSS processors.let postcss = require('postcss')postcss(plugins).process(css, { from, to }).then(result => {console.log(result.css)})Parameter plugins
PostCSS plugins. Processor to process multiple CSS.
function root
root: (defaults?: RootProps) => Root;
Creates a new
Root
node.Parameter defaults
Properties for the new node. New root node.
function rule
rule: (defaults?: RuleProps) => Rule;
Creates a new
Rule
node.Parameter default
Properties for the new node. New rule node.
class AtRule
class AtRule_ extends Container {}
Represents an at-rule.
Once (root, { AtRule }) {let media = new AtRule({ name: 'media', params: 'print' })media.append(…)root.append(media)}If it’s followed in the CSS by a
{}
block, this node will have a nodes property representing its children.const root = postcss.parse('@charset "UTF-8"; @media print {}')const charset = root.firstcharset.type //=> 'atrule'charset.nodes //=> undefinedconst media = root.lastmedia.nodes //=> []
constructor
constructor(defaults?: AtRule.AtRuleProps);
property name
name: string;
The at-rule’s name immediately follows the
@
.const root = postcss.parse('@media print {}')const media = root.firstmedia.name //=> 'media'
property nodes
nodes: Node.ChildNode[];
An array containing the layer’s children.
const root = postcss.parse('@layer example { a { color: black } }')const layer = root.firstlayer.nodes.length //=> 1layer.nodes[0].selector //=> 'a'Can be
undefinded
if the at-rule has no body.const root = postcss.parse('@layer a, b, c;')const layer = root.firstlayer.nodes //=> undefined
property params
params: string;
The at-rule’s parameters, the values that follow the at-rule’s name but precede any
{}
block.const root = postcss.parse('@media print, screen {}')const media = root.firstmedia.params //=> 'print, screen'
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property raws
raws: AtRule.AtRuleRaws;
property type
type: string;
method assign
assign: (overrides: AtRule.AtRuleProps | object) => this;
method clone
clone: (overrides?: Partial<AtRule.AtRuleProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<AtRule.AtRuleProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<AtRule.AtRuleProps>) => this;
class Comment
class Comment_ extends Node {}
It represents a class that handles [CSS comments](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments)
Once (root, { Comment }) {const note = new Comment({ text: 'Note: …' })root.append(note)}Remember that CSS comments inside selectors, at-rule parameters, or declaration values will be stored in the
raws
properties explained above.
constructor
constructor(defaults?: Comment.CommentProps);
property parent
parent: Container<Node.ChildNode>;
property raws
raws: Comment.CommentRaws;
property text
text: string;
The comment's text.
property type
type: string;
method assign
assign: (overrides: Comment.CommentProps | object) => this;
method clone
clone: (overrides?: Partial<Comment.CommentProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Comment.CommentProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Comment.CommentProps>) => this;
class Container
abstract class Container_<Child extends Node = ChildNode> extends Node {}
The
Root
,AtRule
, andRule
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.
property first
readonly first: Node;
The container’s first child.
rule.first === rules.nodes[0]
property last
readonly last: Node;
The container’s last child.
rule.last === rule.nodes[rule.nodes.length - 1]
property nodes
nodes: Child[];
An array containing the container’s children.
const root = postcss.parse('a { color: black }')root.nodes.length //=> 1root.nodes[0].selector //=> 'a'root.nodes[0].nodes[0].prop //=> 'color'
method append
append: (...nodes: Container.NewChild[]) => this;
Inserts new nodes to the end of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })const decl2 = new Declaration({ prop: 'background-color', value: 'white' })rule.append(decl1, decl2)root.append({ name: 'charset', params: '"UTF-8"' }) // at-ruleroot.append({ selector: 'a' }) // rulerule.append({ prop: 'color', value: 'black' }) // declarationrule.append({ text: 'Comment' }) // commentroot.append('a {}')root.first.append('color: black; z-index: 1')Parameter nodes
New nodes. This node for methods chain.
method assign
assign: (overrides: Container.ContainerProps | object) => this;
method clone
clone: (overrides?: Partial<Container.ContainerProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Container.ContainerProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Container.ContainerProps>) => this;
method each
each: ( callback: (node: Child, index: number) => false | void) => false | undefined;
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 orArray#forEach
this iterator is safe if you are mutating the array of child nodes during iteration. PostCSS will adjust the current index to match the mutations.const root = postcss.parse('a { color: black; z-index: 1 }')const rule = root.firstfor (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})Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method every
every: ( condition: (node: Child, index: number, nodes: Child[]) => boolean) => boolean;
Returns
true
if callback returnstrue
for all of the container’s children.const noPrefixes = rule.every(i => i.prop[0] !== '-')Parameter condition
Iterator returns true or false. Is every child pass condition.
method index
index: (child: Child | number) => number;
Returns a
child
’s index within theContainer#nodes
array.rule.index( rule.nodes[2] ) //=> 2Parameter child
Child of the current container. Child index.
method insertAfter
insertAfter: (oldNode: Child | number, newNode: Container.NewChild) => this;
Insert new node after old node within the container.
Parameter oldNode
Child or child’s index.
Parameter newNode
New node. This node for methods chain.
method insertBefore
insertBefore: (oldNode: Child | number, newNode: Container.NewChild) => this;
Insert new node before old node within the container.
rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))Parameter oldNode
Child or child’s index.
Parameter newNode
New node. This node for methods chain.
method normalize
protected normalize: ( nodes: Container.NewChild, sample: Node | undefined, type?: 'prepend' | false) => Child[];
An internal method that converts a NewChild into a list of actual child nodes that can then be added to this container.
This ensures that the nodes' parent is set to this container, that they use the correct prototype chain, and that they're marked as dirty.
Parameter mnodes
The new node or nodes to add.
Parameter sample
A node from whose raws the new node's
before
raw should be taken.Parameter type
This should be set to
'prepend'
if the new nodes will be inserted at the beginning of the container.
method prepend
prepend: (...nodes: Container.NewChild[]) => this;
Inserts new nodes to the start of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })const decl2 = new Declaration({ prop: 'background-color', value: 'white' })rule.prepend(decl1, decl2)root.append({ name: 'charset', params: '"UTF-8"' }) // at-ruleroot.append({ selector: 'a' }) // rulerule.append({ prop: 'color', value: 'black' }) // declarationrule.append({ text: 'Comment' }) // commentroot.append('a {}')root.first.append('color: black; z-index: 1')Parameter nodes
New nodes. This node for methods chain.
method push
push: (child: Child) => this;
Add child to the end of the node.
rule.push(new Declaration({ prop: 'color', value: 'black' }))Parameter child
New node. This node for methods chain.
method removeAll
removeAll: () => this;
Removes all children from the container and cleans their parent properties.
rule.removeAll()rule.nodes.length //=> 0This node for methods chain.
method removeChild
removeChild: (child: Child | number) => this;
Removes node from the container and cleans the parent properties from the node and its children.
rule.nodes.length //=> 5rule.removeChild(decl)rule.nodes.length //=> 4decl.parent //=> undefinedParameter child
Child or child’s index. This node for methods chain.
method replaceValues
replaceValues: { ( pattern: RegExp | string, replaced: string | ((substring: string, ...args: any[]) => string) ): this; ( pattern: string | RegExp, options: Container.ValueOptions, replaced: string | ((substring: string, ...args: any[]) => string) ): this;};
Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.
This method is useful if you are using a custom unit or function and need to iterate through all values.
root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {return 15 * parseInt(string) + 'px'})Parameter pattern
Replace pattern.
Parameter options
Options to speed up the search.
Parameter replaced
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
. This node for methods chain.
method some
some: ( condition: (node: Child, index: number, nodes: Child[]) => boolean) => boolean;
Returns
true
if callback returnstrue
for (at least) one of the container’s children.const hasPrefix = rule.some(i => i.prop[0] === '-')Parameter condition
Iterator returns true or false. Is some child pass condition.
method walk
walk: ( callback: (node: ChildNode, index: number) => false | void) => false | undefined;
Traverses the container’s descendant nodes, calling callback for each node.
Like container.each(), this method is safe to use if you are mutating arrays during iteration.
If you only need to iterate through the container’s immediate children, use
Container#each
.root.walk(node => {// Traverses all descendant nodes.})Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkAtRules
walkAtRules: { ( nameFilter: RegExp | string, callback: (atRule: AtRule, index: number) => false | void ): false | undefined; (callback: (atRule: AtRule, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each at-rule node.
If you pass a filter, iteration will only happen over at-rules that have matching names.
Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.root.walkAtRules(rule => {if (isOld(rule.name)) rule.remove()})let first = falseroot.walkAtRules('charset', rule => {if (!first) {first = true} else {rule.remove()}})Parameter name
String or regular expression to filter at-rules by name.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkComments
walkComments: { (callback: (comment: Comment, indexed: number) => false | void): | false | undefined; (callback: (comment: Comment, indexed: number) => false | void): false;};
method walkDecls
walkDecls: { ( propFilter: RegExp | string, callback: (decl: Declaration, index: number) => false | void ): false | undefined; (callback: (decl: Declaration, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each declaration node.
If you pass a filter, iteration will only happen over declarations with matching properties.
root.walkDecls(decl => {checkPropertySupport(decl.prop)})root.walkDecls('border-radius', decl => {decl.remove()})root.walkDecls(/^background/, decl => {decl.value = takeFirstColorFromGradient(decl.value)})Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.Parameter prop
String or regular expression to filter declarations by property name.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkRules
walkRules: { ( selectorFilter: RegExp | string, callback: (rule: Rule, index: number) => false | void ): false | undefined; (callback: (rule: Rule, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each rule node.
If you pass a filter, iteration will only happen over rules with matching selectors.
Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.const selectors = []root.walkRules(rule => {selectors.push(rule.selector)})console.log(`Your CSS uses ${ selectors.length } selectors`)Parameter selector
String or regular expression to filter rules by selector.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
class CssSyntaxError
class CssSyntaxError_ extends Error {}
The CSS parser throws this error for broken CSS.
Custom parsers can throw this error for broken custom syntax using the
Node#error
method.PostCSS will use the input source map to detect the original error location. If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS, PostCSS will show the original position in the Sass file.
If you need the position in the PostCSS input (e.g., to debug the previous compiler), use
error.input.file
.// Raising error from pluginthrow node.error('Unknown variable', { plugin: 'postcss-vars' })// Catching and checking syntax errortry {postcss.parse('a{')} catch (error) {if (error.name === 'CssSyntaxError') {error //=> CssSyntaxError}}
constructor
constructor( message: string, lineOrStartPos?: number | CssSyntaxError.RangePosition, columnOrEndPos?: number | CssSyntaxError.RangePosition, source?: string, file?: string, plugin?: string);
Instantiates a CSS syntax error. Can be instantiated for a single position or for a range.
Parameter message
Error message.
Parameter lineOrStartPos
If for a single position, the line number, or if for a range, the inclusive start position of the error.
Parameter columnOrEndPos
If for a single position, the column number, or if for a range, the exclusive end position of the error.
Parameter source
Source code of the broken file.
Parameter file
Absolute path to the broken file.
Parameter plugin
PostCSS plugin name, if error came from plugin.
property column
column?: number;
Source column of the error.
error.column //=> 1error.input.column //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.column
.
property endColumn
endColumn?: number;
Source column of the error's end, exclusive. Provided if the error pertains to a range.
error.endColumn //=> 1error.input.endColumn //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.endColumn
.
property endLine
endLine?: number;
Source line of the error's end, exclusive. Provided if the error pertains to a range.
error.endLine //=> 3error.input.endLine //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.endLine
.
property file
file?: string;
Absolute path to the broken file.
error.file //=> 'a.sass'error.input.file //=> 'a.css'PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.file
.
property input
input?: FilePosition;
Input object with PostCSS internal information about input file. If input has source map from previous tool, PostCSS will use origin (for example, Sass) source. You can use this object to get PostCSS input source.
error.input.file //=> 'a.css'error.file //=> 'a.sass'
property line
line?: number;
Source line of the error.
error.line //=> 2error.input.line //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.line
.
property message
message: string;
Full error text in the GNU error format with plugin, file, line and column.
error.message //=> 'a.css:1:1: Unclosed block'
property name
name: string;
Always equal to
'CssSyntaxError'
. You should always check error type byerror.name === 'CssSyntaxError'
instead oferror instanceof CssSyntaxError
, because npm could have several PostCSS versions.if (error.name === 'CssSyntaxError') {error //=> CssSyntaxError}
property plugin
plugin?: string;
Plugin name, if error came from plugin.
error.plugin //=> 'postcss-vars'
property reason
reason: string;
Error message.
error.message //=> 'Unclosed block'
property source
source?: string;
Source code of the broken file.
error.source //=> 'a { b {} }'error.input.source //=> 'a b { }'
property stack
stack: string;
method showSourceCode
showSourceCode: (color?: boolean) => string;
Returns a few lines of CSS source that caused the error.
If the CSS has an input source map without
sourceContent
, this method will return an empty string.error.showSourceCode() //=> " 4 | }// 5 | a {// > 6 | bad// | ^// 7 | }// 8 | b {"Parameter color
Whether arrow will be colored red by terminal color codes. By default, PostCSS will detect color support by
process.stdout.isTTY
andprocess.env.NODE_DISABLE_COLORS
. Few lines of CSS source that caused the error.
method toString
toString: () => string;
Returns error position, message and source code of the broken part.
error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block// > 1 | a {// | ^"Error position, message and source code.
class Declaration
class Declaration_ extends Node {}
It represents a class that handles [CSS declarations](https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_declarations)
Once (root, { Declaration }) {const color = new Declaration({ prop: 'color', value: 'black' })root.append(color)}const root = postcss.parse('a { color: black }')const decl = root.first?.firstdecl.type //=> 'decl'decl.toString() //=> ' color: black'
constructor
constructor(defaults?: Declaration.DeclarationProps);
property important
important: boolean;
It represents a specificity of the declaration.
If true, the CSS declaration will have an [important](https://developer.mozilla.org/en-US/docs/Web/CSS/important) specifier.
const root = postcss.parse('a { color: black !important; color: red }')root.first.first.important //=> trueroot.first.last.important //=> undefined
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property prop
prop: string;
The property name for a CSS declaration.
const root = postcss.parse('a { color: black }')const decl = root.first.firstdecl.prop //=> 'color'
property raws
raws: Declaration.DeclarationRaws;
property type
type: string;
property value
value: string;
The property value for a CSS declaration.
Any CSS comments inside the value string will be filtered out. CSS comments present in the source value will be available in the
raws
property.Assigning new
value
would ignore the comments inraws
property while compiling node to string.const root = postcss.parse('a { color: black }')const decl = root.first.firstdecl.value //=> 'black'
property variable
readonly variable: boolean;
It represents a getter that returns
true
if a declaration starts with--
or$
, which are used to declare variables in CSS and SASS/SCSS.const root = postcss.parse(':root { --one: 1 }')const one = root.first.firstone.variable //=> trueconst root = postcss.parse('$one: 1')const one = root.firstone.variable //=> true
method assign
assign: (overrides: Declaration.DeclarationProps | object) => this;
method clone
clone: (overrides?: Partial<Declaration.DeclarationProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Declaration.DeclarationProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Declaration.DeclarationProps>) => this;
class Document
class Document_ extends Container<Root> {}
Represents a file and contains all its parsed nodes.
**Experimental:** some aspects of this node could change within minor or patch version releases.
const document = htmlParser('<html><style>a{color:black}</style><style>b{z-index:2}</style>')document.type //=> 'document'document.nodes.length //=> 2
constructor
constructor(defaults?: Document.DocumentProps);
property nodes
nodes: Root[];
property parent
parent: undefined;
property type
type: string;
method assign
assign: (overrides: Document.DocumentProps | object) => this;
method clone
clone: (overrides?: Partial<Document.DocumentProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Document.DocumentProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Document.DocumentProps>) => this;
method toResult
toResult: (options?: ProcessOptions) => Result;
Returns a
Result
instance representing the document’s CSS roots.const root1 = postcss.parse(css1, { from: 'a.css' })const root2 = postcss.parse(css2, { from: 'b.css' })const document = postcss.document()document.append(root1)document.append(root2)const result = document.toResult({ to: 'all.css', map: true })Parameter opts
Options. Result with current document’s CSS.
class Input
class Input_ {}
Represents the source CSS.
const root = postcss.parse(css, { from: file })const input = root.source.input
constructor
constructor(css: string, opts?: ProcessOptions<Document_ | Root_>);
Parameter css
Input CSS source.
Parameter opts
Process options.
property css
css: string;
Input CSS source.
const input = postcss.parse('a{}', { from: file }).inputinput.css //=> "a{}"
property file
file?: string;
The absolute path to the CSS source file defined with the
from
option.const root = postcss.parse(css, { from: 'a.css' })root.source.input.file //=> '/home/ai/a.css'
property from
readonly from: string;
The CSS source identifier. Contains
Input#file
if the user set thefrom
option, orInput#id
if they did not.const root = postcss.parse(css, { from: 'a.css' })root.source.input.from //=> "/home/ai/a.css"const root = postcss.parse(css)root.source.input.from //=> "<input css 1>"
property hasBOM
hasBOM: boolean;
The flag to indicate whether or not the source code has Unicode BOM.
property id
id?: string;
The unique ID of the CSS source. It will be created if
from
option is not provided (because PostCSS does not know the file path).const root = postcss.parse(css)root.source.input.file //=> undefinedroot.source.input.id //=> "<input css 8LZeVF>"
property map
map: PreviousMap;
The input source map passed from a compilation step before PostCSS (for example, from Sass compiler).
root.source.input.map.consumer().sources //=> ['a.sass']
method error
error: { ( message: string, start: { column: number; line: number } | { offset: number }, end: { column: number; line: number } | { offset: number }, opts?: { plugin?: CssSyntaxError['plugin'] } ): CssSyntaxError; ( message: string, line: number, column: number, opts?: { plugin?: string } ): CssSyntaxError; ( message: string, offset: number, opts?: { plugin?: string } ): CssSyntaxError;};
Returns
CssSyntaxError
with information about the error and its position.
method fromOffset
fromOffset: (offset: number) => { col: number; line: number } | null;
Converts source offset to line and column.
Parameter offset
Source offset.
method origin
origin: ( line: number, column: number, endLine?: number, endColumn?: number) => false | Input.FilePosition;
Reads the input source map and returns a symbol position in the input source (e.g., in a Sass file that was compiled to CSS before being passed to PostCSS). Optionally takes an end position, exclusive.
root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }root.source.input.origin(1, 1, 1, 4)//=> { file: 'a.css', line: 3, column: 1, endLine: 3, endColumn: 4 }Parameter line
Line for inclusive start position in input CSS.
Parameter column
Column for inclusive start position in input CSS.
Parameter endLine
Line for exclusive end position in input CSS.
Parameter endColumn
Column for exclusive end position in input CSS.
Position in input source.
method toJSON
toJSON: () => object;
Converts this to a JSON-friendly object representation.
class LazyResult
class LazyResult_<RootNode = Document | Root> implements PromiseLike<Result<RootNode>> {}
A Promise proxy for the result of PostCSS transformations.
A
LazyResult
instance is returned byProcessor#process
.const lazy = postcss([autoprefixer]).process(css)
constructor
constructor(processor: Processor, css: string, opts: ResultOptions);
Parameter processor
Processor used for this transformation.
Parameter css
CSS to parse and transform.
Parameter opts
Options from the
Processor#process
orRoot#toResult
.
property [Symbol.toStringTag]
readonly [Symbol.toStringTag]: string;
Returns the default string description of an object. Required to implement the Promise interface.
property catch
catch: <TResult = never>( onrejected?: (reason: any) => TResult | PromiseLike<TResult>) => Promise<Result<RootNode> | TResult>;
Processes input CSS through synchronous and asynchronous plugins and calls onRejected for each error thrown in any plugin.
It implements standard Promise API.
postcss([autoprefixer]).process(css).then(result => {console.log(result.css)}).catch(error => {console.error(error)})
property content
readonly content: string;
An alias for the
css
property. Use it with syntaxes that generate non-CSS output.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property css
readonly css: string;
Processes input CSS through synchronous plugins, converts
Root
to a CSS string and returnsResult#css
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property finally
finally: (onfinally?: () => void) => Promise<Result<RootNode>>;
Processes input CSS through synchronous and asynchronous plugins and calls onFinally on any error or when all plugins will finish work.
It implements standard Promise API.
postcss([autoprefixer]).process(css).finally(() => {console.log('processing ended')})
property map
readonly map: any;
Processes input CSS through synchronous plugins and returns
Result#map
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property messages
readonly messages: Message[];
Processes input CSS through synchronous plugins and returns
Result#messages
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property opts
readonly opts: ResultOptions;
Options from the
Processor#process
call.
property processor
readonly processor: Processor;
Returns a
Processor
instance, which will be used for CSS transformations.
property root
readonly root: {};
Processes input CSS through synchronous plugins and returns
Result#root
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property then
then: <TResult1 = Result<RootNode>, TResult2 = never>( onfulfilled?: (value: Result<RootNode>) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<TResult1 | TResult2>;
Processes input CSS through synchronous and asynchronous plugins and calls
onFulfilled
with a Result instance. If a plugin throws an error, theonRejected
callback will be executed.It implements standard Promise API.
postcss([autoprefixer]).process(css, { from: cssPath }).then(result => {console.log(result.css)})
method async
async: () => Promise<Result<RootNode>>;
Run plugin in async way and return
Result
.Result with output content.
method sync
sync: () => Result<RootNode>;
Run plugin in sync way and return
Result
.Result with output content.
method toString
toString: () => string;
Alias for the
LazyResult#css
property.lazy + '' === lazy.cssOutput CSS.
method warnings
warnings: () => Warning[];
Processes input CSS through synchronous plugins and calls
Result#warnings
.Warnings from plugins.
class Node
class Node extends Node_ {}
class Processor
class Processor_ {}
Contains plugins to process CSS. Create one
Processor
instance, initialize its plugins, and then use that instance on numerous CSS files.const processor = postcss([autoprefixer, postcssNested])processor.process(css1).then(result => console.log(result.css))processor.process(css2).then(result => console.log(result.css))
constructor
constructor(plugins?: readonly AcceptedPlugin[]);
Parameter plugins
PostCSS plugins
property plugins
plugins: (Plugin | TransformCallback | Transformer)[];
Plugins added to this processor.
const processor = postcss([autoprefixer, postcssNested])processor.plugins.length //=> 2
property version
version: string;
Current PostCSS version.
if (result.processor.version.split('.')[0] !== '6') {throw new Error('This plugin works only with PostCSS 6')}
method process
process: { (css: { toString(): string } | LazyResult | Result | Root | string): | LazyResult | NoWorkResult; <RootNode extends Document | Root = Root>( css: | string | Root | Result<Document | Root> | LazyResult<Document | Root> | { toString(): string }, options: ProcessOptions<RootNode> ): LazyResult<RootNode>;};
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 theLazyResult
methods.processor.process(css, { from: 'a.css', to: 'a.out.css' }).then(result => {console.log(result.css)})Parameter css
String with input CSS or any object with a
toString()
method, like a Buffer. Optionally, send aResult
instance and the processor will take theRoot
from it.Parameter opts
Options. Promise proxy.
method use
use: (plugin: AcceptedPlugin) => this;
Adds a plugin to be used as a CSS processor.
PostCSS plugin can be in 4 formats: * A plugin in
Plugin
format. * A plugin creator function withpluginCreator.postcss = true
. PostCSS will call this function without argument to get plugin. * A function. PostCSS will pass the function a Root as the first argument and currentResult
instance as the second. * AnotherProcessor
instance. PostCSS will copy plugins from that instance into this one.Plugins can also be added by passing them as arguments when creating a
postcss
instance (see [postcss(plugins)
]).Asynchronous plugins should return a
Promise
instance.const processor = postcss().use(autoprefixer).use(postcssNested)Parameter plugin
PostCSS plugin or
Processor
with plugins. Current processor to make methods chain.
class Result
class Result_<RootNode = Document | Root> {}
Provides the result of the PostCSS transformations.
A Result instance is returned by
LazyResult#then
orRoot#toResult
methods.postcss([autoprefixer]).process(css).then(result => {console.log(result.css)})const result2 = postcss.parse(css).toResult()
constructor
constructor(processor: Processor, root: {}, opts: Result.ResultOptions);
Parameter processor
Processor used for this transformation.
Parameter root
Root node after all transformations.
Parameter opts
Options from the
Processor#process
orRoot#toResult
.
property content
readonly content: string;
An alias for the
Result#css
property. Use it with syntaxes that generate non-CSS output.result.css === result.content
property css
css: string;
A CSS string representing of
Result#root
.postcss.parse('a{}').toResult().css //=> "a{}"
property lastPlugin
lastPlugin: Plugin | TransformCallback;
Last runned PostCSS plugin.
property map
map: any;
An instance of
SourceMapGenerator
class from thesource-map
library, representing changes to theResult#root
instance.result.map.toJSON() //=> { version: 3, file: 'a.css', … }if (result.map) {fs.writeFileSync(result.opts.to + '.map', result.map.toString())}
property messages
messages: Result.Message[];
Contains messages from plugins (e.g., warnings or custom messages). Each message should have type and plugin properties.
AtRule: {import: (atRule, { result }) {const importedFile = parseImport(atRule)result.messages.push({type: 'dependency',plugin: 'postcss-import',file: importedFile,parent: result.opts.from})}}
property opts
opts: Result.ResultOptions;
Options from the
Processor#process
orRoot#toResult
call that produced this Result instance.]root.toResult(opts).opts === opts
property processor
processor: Processor;
The Processor instance used for this transformation.
for (const plugin of result.processor.plugins) {if (plugin.postcssPlugin === 'postcss-bad') {throw 'postcss-good is incompatible with postcss-bad'}})
property root
root: {};
Root node after all transformations.
root.toResult().root === root
method toString
toString: () => string;
Returns for
Result#css
content.result + '' === result.cssString representing of
Result#root
.
method warn
warn: (message: string, options?: WarningOptions) => Warning;
Creates an instance of
Warning
and adds it toResult#messages
.if (decl.important) {result.warn('Avoid !important', { node: decl, word: '!important' })}Parameter text
Warning message.
Parameter opts
Warning options. Created warning.
method warnings
warnings: () => Warning[];
Returns warnings from plugins. Filters
Warning
instances fromResult#messages
.result.warnings().forEach(warn => {console.warn(warn.toString())})Warnings from plugins.
class Root
class Root_ extends Container {}
Represents a CSS file and contains all its parsed nodes.
const root = postcss.parse('a{color:black} b{z-index:2}')root.type //=> 'root'root.nodes.length //=> 2
constructor
constructor(defaults?: Root.RootProps);
property nodes
nodes: Node.ChildNode[];
property parent
parent: Document;
property raws
raws: Root.RootRaws;
property type
type: string;
method assign
assign: (overrides: object | Root.RootProps) => this;
method clone
clone: (overrides?: Partial<Root.RootProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Root.RootProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Root.RootProps>) => this;
method toResult
toResult: (options?: ProcessOptions) => Result;
Returns a
Result
instance representing the root’s CSS.const root1 = postcss.parse(css1, { from: 'a.css' })const root2 = postcss.parse(css2, { from: 'b.css' })root1.append(root2)const result = root1.toResult({ to: 'all.css', map: true })Parameter options
Options. Result with current root’s CSS.
class Rule
class Rule_ extends Container {}
Represents a CSS rule: a selector followed by a declaration block.
Once (root, { Rule }) {let a = new Rule({ selector: 'a' })a.append(…)root.append(a)}const root = postcss.parse('a{}')const rule = root.firstrule.type //=> 'rule'rule.toString() //=> 'a{}'
constructor
constructor(defaults?: Rule.RuleProps);
property nodes
nodes: Node.ChildNode[];
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property raws
raws: Rule.RuleRaws;
property selector
selector: string;
The rule’s full selector represented as a string.
const root = postcss.parse('a, b { }')const rule = root.firstrule.selector //=> 'a, b'
property selectors
selectors: string[];
An array containing the rule’s individual selectors. Groups of selectors are split at commas.
const root = postcss.parse('a, b { }')const rule = root.firstrule.selector //=> 'a, b'rule.selectors //=> ['a', 'b']rule.selectors = ['a', 'strong']rule.selector //=> 'a, strong'
property type
type: string;
method assign
assign: (overrides: object | Rule.RuleProps) => this;
method clone
clone: (overrides?: Partial<Rule.RuleProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Rule.RuleProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Rule.RuleProps>) => this;
class Warning
class Warning_ {}
Represents a plugin’s warning. It can be created using
Node#warn
.if (decl.important) {decl.warn(result, 'Avoid !important', { word: '!important' })}
constructor
constructor(text: string, opts?: Warning.WarningOptions);
Parameter text
Warning message.
Parameter opts
Warning options.
property column
column: number;
Column for inclusive start position in the input file with this warning’s source.
warning.column //=> 6
property endColumn
endColumn?: number;
Column for exclusive end position in the input file with this warning’s source.
warning.endColumn //=> 4
property endLine
endLine?: number;
Line for exclusive end position in the input file with this warning’s source.
warning.endLine //=> 6
property line
line: number;
Line for inclusive start position in the input file with this warning’s source.
warning.line //=> 5
property node
node: Node;
Contains the CSS node that caused the warning.
warning.node.toString() //=> 'color: white !important'
property plugin
plugin: string;
The name of the plugin that created this warning. When you call
Node#warn
it will fill this property automatically.warning.plugin //=> 'postcss-important'
property text
text: string;
The warning message.
warning.text //=> 'Try to avoid !important'
property type
type: string;
Type to filter warnings from
Result#messages
. Always equal to"warning"
.
method toString
toString: () => string;
Returns a warning position and message.
warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'Warning position and message.
interface AtRuleProps
interface AtRuleProps extends ContainerProps {}
interface Builder
interface Builder {}
call signature
(part: string, node?: AnyNode, type?: 'end' | 'start'): void;
interface CommentProps
interface CommentProps extends NodeProps {}
interface ContainerProps
interface ContainerProps extends NodeProps {}
property nodes
nodes?: readonly (ChildProps | Node)[];
interface DeclarationProps
interface DeclarationProps {}
property important
important?: boolean;
Whether the declaration has an
!important
annotation.
property prop
prop: string;
Name of the declaration.
property raws
raws?: DeclarationRaws;
Information used to generate byte-to-byte equal node string as it was in the origin input.
property value
value: string;
Value of the declaration.
interface DocumentProps
interface DocumentProps extends ContainerProps {}
interface FilePosition
interface FilePosition {}
property column
column: number;
Column of inclusive start position in source file.
property endColumn
endColumn?: number;
Column of exclusive end position in source file.
property endLine
endLine?: number;
Line of exclusive end position in source file.
property file
file?: string;
Absolute path to the source file.
property line
line: number;
Line of inclusive start position in source file.
property source
source?: string;
Source code.
property url
url: string;
URL for the source file.
interface JSONHydrator
interface JSONHydrator {}
call signature
(data: object): Node;
call signature
(data: object[]): Node[];
interface Message
interface Message {}
property plugin
plugin?: string;
Source PostCSS plugin name.
property type
type: string;
Message type.
index signature
[others: string]: any;
interface NodeErrorOptions
interface NodeErrorOptions {}
property endIndex
endIndex?: number;
An ending index inside a node's string that should be highlighted as source of error.
property index
index?: number;
An index inside a node's string that should be highlighted as source of error.
property plugin
plugin?: string;
Plugin name that created this error. PostCSS will set it automatically.
property word
word?: string;
A word inside a node's string, that should be highlighted as source of error.
interface NodeProps
interface NodeProps {}
Interface represents an interface for an object received as parameter by Node class constructor.
property source
source?: Source;
interface OldPlugin
interface OldPlugin<T> extends Transformer {}
property postcss
postcss: Transformer;
call signature
(opts?: T): Transformer;
interface Parser
interface Parser<RootNode = Document | Root> {}
call signature
( css: { toString(): string } | string, opts?: Pick<ProcessOptions, 'from' | 'map'>): RootNode;
interface Plugin
interface Plugin extends Processors {}
property postcssPlugin
postcssPlugin: string;
property prepare
prepare?: (result: Result) => Processors;
interface PluginCreator
interface PluginCreator<PluginOptions> {}
property postcss
postcss: true;
call signature
(opts?: PluginOptions): Plugin | Processor;
interface Position
interface Position {}
interface ProcessOptions
interface ProcessOptions<RootNode = Document | Root> {}
property from
from?: string | undefined;
The path of the CSS source file. You should always set
from
, because it is used in source map generation and syntax error messages.
property map
map?: boolean | SourceMapOptions;
Source map options
property parser
parser?: Parser<RootNode> | Syntax<RootNode>;
Function to generate AST by string.
property stringifier
stringifier?: Stringifier | Syntax<RootNode>;
Class to generate string by AST.
property syntax
syntax?: Syntax<RootNode>;
Object with parse and stringify.
property to
to?: string;
The path where you'll put the output CSS file. You should always set
to
to generate correct source maps.
interface RootProps
interface RootProps extends ContainerProps {}
property raws
raws?: RootRaws;
Information used to generate byte-to-byte equal node string as it was in the origin input.
interface Source
interface Source {}
Source represents an interface for the Node.source property.
interface SourceMapOptions
interface SourceMapOptions {}
property absolute
absolute?: boolean;
Use absolute path in generated source map.
property annotation
annotation?: ((file: string, root: Root) => string) | boolean | string;
Indicates that PostCSS should add annotation comments to the CSS. By default, PostCSS will always add a comment with a path to the source map. PostCSS will not add annotations to CSS files that do not contain any comments.
By default, PostCSS presumes that you want to save the source map as
opts.to + '.map'
and will use this path in the annotation comment. A different path can be set by providing a string value for annotation.If you have set
inline: true
, annotation cannot be disabled.
property from
from?: string;
Override
from
in map’s sources.
property inline
inline?: boolean;
Indicates that the source map should be embedded in the output CSS as a Base64-encoded comment. By default, it is
true
. But if all previous maps are external, not inline, PostCSS will not embed the map even if you do not set this option.If you have an inline source map, the result.map property will be empty, as the source map will be contained within the text of
result.css
.
property prev
prev?: ((file: string) => string) | boolean | object | string;
Source map content from a previous processing step (e.g., Sass).
PostCSS will try to read the previous source map automatically (based on comments within the source CSS), but you can use this option to identify it manually.
If desired, you can omit the previous map with prev:
false
.
property sourcesContent
sourcesContent?: boolean;
Indicates that PostCSS should set the origin content (e.g., Sass source) of the source map. By default, it is true. But if all previous maps do not contain sources content, PostCSS will also leave it out even if you do not set this option.
interface Stringifier
interface Stringifier {}
call signature
(node: AnyNode, builder: Builder): void;
interface Syntax
interface Syntax<RootNode = Document | Root> {}
interface TransformCallback
interface TransformCallback {}
call signature
(root: Root, result: Result): Promise<void> | void;
interface Transformer
interface Transformer extends TransformCallback {}
property postcssPlugin
postcssPlugin: string;
property postcssVersion
postcssVersion: string;
interface WarningOptions
interface WarningOptions {}
property end
end?: RangePosition;
End position, exclusive, in CSS node string that caused the warning.
property endIndex
endIndex?: number;
End index, exclusive, in CSS node string that caused the warning.
property index
index?: number;
Start index, inclusive, in CSS node string that caused the warning.
property node
node?: Node;
CSS node that caused the warning.
property plugin
plugin?: string;
Name of the plugin that created this warning.
Result#warn
fills this property automatically.
property start
start?: RangePosition;
Start position, inclusive, in CSS node string that caused the warning.
property word
word?: string;
Word in CSS source that caused the warning.
type AcceptedPlugin
type AcceptedPlugin = | { postcss: Processor | TransformCallback; } | OldPlugin<any> | Plugin | PluginCreator<any> | Processor | TransformCallback;
type AnyNode
type AnyNode = AtRule.default | Comment | Declaration | Document | Root | Rule;
type ChildNode
type ChildNode = AtRule.default | Comment | Declaration | Rule;
type ChildProps
type ChildProps = AtRuleProps | CommentProps | DeclarationProps | RuleProps;
type Helpers
type Helpers = { postcss: Postcss; result: Result } & Postcss;
type NewChild
type NewChild = | ChildProps | Node | readonly ChildProps[] | readonly Node[] | readonly string[] | string | undefined;
All types that can be passed into container methods to create or add a new child node.
type Postcss
type Postcss = typeof postcss;
type RuleProps
type RuleProps = { /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ raws?: RuleRaws;} & ( | { /** Selector or selectors of the rule. */ selector: string; selectors?: never; } | { selector?: never; /** Selectors of the rule represented as an array of strings. */ selectors: readonly string[]; }) & ContainerProps;
type SourceMap
type SourceMap = { toJSON(): RawSourceMap;} & SourceMapGenerator;
namespace postcss.postcss.postcss.postcss.postcss
namespace postcss.postcss.postcss.postcss.postcss {}
variable fromJSON
let fromJSON: JSONHydrator;
Rehydrate a JSON AST (from
Node#toJSON
) back into the AST classes.const json = root.toJSON()// save to file, send by network, etcconst root2 = postcss.fromJSON(json)
variable parse
let parse: Parser<Root>;
Parses source css and returns a new
Root
orDocument
node, which contains the source CSS nodes.// Simple CSS concatenation with source map supportconst root1 = postcss.parse(css1, { from: file1 })const root2 = postcss.parse(css2, { from: file2 })root1.append(root2).toResult().css
variable stringify
let stringify: Stringifier;
Default function to convert a node tree into a CSS string.
function atRule
atRule: (defaults?: AtRuleProps) => AtRule;
Creates a new
AtRule
node.Parameter defaults
Properties for the new node. New at-rule node.
function comment
comment: (defaults?: CommentProps) => Comment;
Creates a new
Comment
node.Parameter defaults
Properties for the new node. New comment node
function decl
decl: (defaults?: DeclarationProps) => Declaration;
Creates a new
Declaration
node.Parameter defaults
Properties for the new node. New declaration node.
function document
document: (defaults?: DocumentProps) => Document;
Creates a new
Document
node.Parameter defaults
Properties for the new node. New document node.
function postcss
postcss: typeof postcss;
Create a new
Processor
instance that will applyplugins
as CSS processors.let postcss = require('postcss')postcss(plugins).process(css, { from, to }).then(result => {console.log(result.css)})Parameter plugins
PostCSS plugins. Processor to process multiple CSS.
function root
root: (defaults?: RootProps) => Root;
Creates a new
Root
node.Parameter defaults
Properties for the new node. New root node.
function rule
rule: (defaults?: RuleProps) => Rule;
Creates a new
Rule
node.Parameter default
Properties for the new node. New rule node.
class AtRule
class AtRule_ extends Container {}
Represents an at-rule.
Once (root, { AtRule }) {let media = new AtRule({ name: 'media', params: 'print' })media.append(…)root.append(media)}If it’s followed in the CSS by a
{}
block, this node will have a nodes property representing its children.const root = postcss.parse('@charset "UTF-8"; @media print {}')const charset = root.firstcharset.type //=> 'atrule'charset.nodes //=> undefinedconst media = root.lastmedia.nodes //=> []
constructor
constructor(defaults?: AtRule.AtRuleProps);
property name
name: string;
The at-rule’s name immediately follows the
@
.const root = postcss.parse('@media print {}')const media = root.firstmedia.name //=> 'media'
property nodes
nodes: Node.ChildNode[];
An array containing the layer’s children.
const root = postcss.parse('@layer example { a { color: black } }')const layer = root.firstlayer.nodes.length //=> 1layer.nodes[0].selector //=> 'a'Can be
undefinded
if the at-rule has no body.const root = postcss.parse('@layer a, b, c;')const layer = root.firstlayer.nodes //=> undefined
property params
params: string;
The at-rule’s parameters, the values that follow the at-rule’s name but precede any
{}
block.const root = postcss.parse('@media print, screen {}')const media = root.firstmedia.params //=> 'print, screen'
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property raws
raws: AtRule.AtRuleRaws;
property type
type: string;
method assign
assign: (overrides: AtRule.AtRuleProps | object) => this;
method clone
clone: (overrides?: Partial<AtRule.AtRuleProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<AtRule.AtRuleProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<AtRule.AtRuleProps>) => this;
class Comment
class Comment_ extends Node {}
It represents a class that handles [CSS comments](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments)
Once (root, { Comment }) {const note = new Comment({ text: 'Note: …' })root.append(note)}Remember that CSS comments inside selectors, at-rule parameters, or declaration values will be stored in the
raws
properties explained above.
constructor
constructor(defaults?: Comment.CommentProps);
property parent
parent: Container<Node.ChildNode>;
property raws
raws: Comment.CommentRaws;
property text
text: string;
The comment's text.
property type
type: string;
method assign
assign: (overrides: Comment.CommentProps | object) => this;
method clone
clone: (overrides?: Partial<Comment.CommentProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Comment.CommentProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Comment.CommentProps>) => this;
class Container
abstract class Container_<Child extends Node = ChildNode> extends Node {}
The
Root
,AtRule
, andRule
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.
property first
readonly first: Node;
The container’s first child.
rule.first === rules.nodes[0]
property last
readonly last: Node;
The container’s last child.
rule.last === rule.nodes[rule.nodes.length - 1]
property nodes
nodes: Child[];
An array containing the container’s children.
const root = postcss.parse('a { color: black }')root.nodes.length //=> 1root.nodes[0].selector //=> 'a'root.nodes[0].nodes[0].prop //=> 'color'
method append
append: (...nodes: Container.NewChild[]) => this;
Inserts new nodes to the end of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })const decl2 = new Declaration({ prop: 'background-color', value: 'white' })rule.append(decl1, decl2)root.append({ name: 'charset', params: '"UTF-8"' }) // at-ruleroot.append({ selector: 'a' }) // rulerule.append({ prop: 'color', value: 'black' }) // declarationrule.append({ text: 'Comment' }) // commentroot.append('a {}')root.first.append('color: black; z-index: 1')Parameter nodes
New nodes. This node for methods chain.
method assign
assign: (overrides: Container.ContainerProps | object) => this;
method clone
clone: (overrides?: Partial<Container.ContainerProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Container.ContainerProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Container.ContainerProps>) => this;
method each
each: ( callback: (node: Child, index: number) => false | void) => false | undefined;
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 orArray#forEach
this iterator is safe if you are mutating the array of child nodes during iteration. PostCSS will adjust the current index to match the mutations.const root = postcss.parse('a { color: black; z-index: 1 }')const rule = root.firstfor (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})Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method every
every: ( condition: (node: Child, index: number, nodes: Child[]) => boolean) => boolean;
Returns
true
if callback returnstrue
for all of the container’s children.const noPrefixes = rule.every(i => i.prop[0] !== '-')Parameter condition
Iterator returns true or false. Is every child pass condition.
method index
index: (child: Child | number) => number;
Returns a
child
’s index within theContainer#nodes
array.rule.index( rule.nodes[2] ) //=> 2Parameter child
Child of the current container. Child index.
method insertAfter
insertAfter: (oldNode: Child | number, newNode: Container.NewChild) => this;
Insert new node after old node within the container.
Parameter oldNode
Child or child’s index.
Parameter newNode
New node. This node for methods chain.
method insertBefore
insertBefore: (oldNode: Child | number, newNode: Container.NewChild) => this;
Insert new node before old node within the container.
rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))Parameter oldNode
Child or child’s index.
Parameter newNode
New node. This node for methods chain.
method normalize
protected normalize: ( nodes: Container.NewChild, sample: Node | undefined, type?: 'prepend' | false) => Child[];
An internal method that converts a NewChild into a list of actual child nodes that can then be added to this container.
This ensures that the nodes' parent is set to this container, that they use the correct prototype chain, and that they're marked as dirty.
Parameter mnodes
The new node or nodes to add.
Parameter sample
A node from whose raws the new node's
before
raw should be taken.Parameter type
This should be set to
'prepend'
if the new nodes will be inserted at the beginning of the container.
method prepend
prepend: (...nodes: Container.NewChild[]) => this;
Inserts new nodes to the start of the container.
const decl1 = new Declaration({ prop: 'color', value: 'black' })const decl2 = new Declaration({ prop: 'background-color', value: 'white' })rule.prepend(decl1, decl2)root.append({ name: 'charset', params: '"UTF-8"' }) // at-ruleroot.append({ selector: 'a' }) // rulerule.append({ prop: 'color', value: 'black' }) // declarationrule.append({ text: 'Comment' }) // commentroot.append('a {}')root.first.append('color: black; z-index: 1')Parameter nodes
New nodes. This node for methods chain.
method push
push: (child: Child) => this;
Add child to the end of the node.
rule.push(new Declaration({ prop: 'color', value: 'black' }))Parameter child
New node. This node for methods chain.
method removeAll
removeAll: () => this;
Removes all children from the container and cleans their parent properties.
rule.removeAll()rule.nodes.length //=> 0This node for methods chain.
method removeChild
removeChild: (child: Child | number) => this;
Removes node from the container and cleans the parent properties from the node and its children.
rule.nodes.length //=> 5rule.removeChild(decl)rule.nodes.length //=> 4decl.parent //=> undefinedParameter child
Child or child’s index. This node for methods chain.
method replaceValues
replaceValues: { ( pattern: RegExp | string, replaced: string | ((substring: string, ...args: any[]) => string) ): this; ( pattern: string | RegExp, options: Container.ValueOptions, replaced: string | ((substring: string, ...args: any[]) => string) ): this;};
Passes all declaration values within the container that match pattern through callback, replacing those values with the returned result of callback.
This method is useful if you are using a custom unit or function and need to iterate through all values.
root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {return 15 * parseInt(string) + 'px'})Parameter pattern
Replace pattern.
Parameter options
Options to speed up the search.
Parameter replaced
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
. This node for methods chain.
method some
some: ( condition: (node: Child, index: number, nodes: Child[]) => boolean) => boolean;
Returns
true
if callback returnstrue
for (at least) one of the container’s children.const hasPrefix = rule.some(i => i.prop[0] === '-')Parameter condition
Iterator returns true or false. Is some child pass condition.
method walk
walk: ( callback: (node: ChildNode, index: number) => false | void) => false | undefined;
Traverses the container’s descendant nodes, calling callback for each node.
Like container.each(), this method is safe to use if you are mutating arrays during iteration.
If you only need to iterate through the container’s immediate children, use
Container#each
.root.walk(node => {// Traverses all descendant nodes.})Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkAtRules
walkAtRules: { ( nameFilter: RegExp | string, callback: (atRule: AtRule, index: number) => false | void ): false | undefined; (callback: (atRule: AtRule, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each at-rule node.
If you pass a filter, iteration will only happen over at-rules that have matching names.
Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.root.walkAtRules(rule => {if (isOld(rule.name)) rule.remove()})let first = falseroot.walkAtRules('charset', rule => {if (!first) {first = true} else {rule.remove()}})Parameter name
String or regular expression to filter at-rules by name.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkComments
walkComments: { (callback: (comment: Comment, indexed: number) => false | void): | false | undefined; (callback: (comment: Comment, indexed: number) => false | void): false;};
method walkDecls
walkDecls: { ( propFilter: RegExp | string, callback: (decl: Declaration, index: number) => false | void ): false | undefined; (callback: (decl: Declaration, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each declaration node.
If you pass a filter, iteration will only happen over declarations with matching properties.
root.walkDecls(decl => {checkPropertySupport(decl.prop)})root.walkDecls('border-radius', decl => {decl.remove()})root.walkDecls(/^background/, decl => {decl.value = takeFirstColorFromGradient(decl.value)})Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.Parameter prop
String or regular expression to filter declarations by property name.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
method walkRules
walkRules: { ( selectorFilter: RegExp | string, callback: (rule: Rule, index: number) => false | void ): false | undefined; (callback: (rule: Rule, index: number) => false | void): false;};
Traverses the container’s descendant nodes, calling callback for each rule node.
If you pass a filter, iteration will only happen over rules with matching selectors.
Like
Container#each
, this method is safe to use if you are mutating arrays during iteration.const selectors = []root.walkRules(rule => {selectors.push(rule.selector)})console.log(`Your CSS uses ${ selectors.length } selectors`)Parameter selector
String or regular expression to filter rules by selector.
Parameter callback
Iterator receives each node and index. Returns
false
if iteration was broke.
class CssSyntaxError
class CssSyntaxError_ extends Error {}
The CSS parser throws this error for broken CSS.
Custom parsers can throw this error for broken custom syntax using the
Node#error
method.PostCSS will use the input source map to detect the original error location. If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS, PostCSS will show the original position in the Sass file.
If you need the position in the PostCSS input (e.g., to debug the previous compiler), use
error.input.file
.// Raising error from pluginthrow node.error('Unknown variable', { plugin: 'postcss-vars' })// Catching and checking syntax errortry {postcss.parse('a{')} catch (error) {if (error.name === 'CssSyntaxError') {error //=> CssSyntaxError}}
constructor
constructor( message: string, lineOrStartPos?: number | CssSyntaxError.RangePosition, columnOrEndPos?: number | CssSyntaxError.RangePosition, source?: string, file?: string, plugin?: string);
Instantiates a CSS syntax error. Can be instantiated for a single position or for a range.
Parameter message
Error message.
Parameter lineOrStartPos
If for a single position, the line number, or if for a range, the inclusive start position of the error.
Parameter columnOrEndPos
If for a single position, the column number, or if for a range, the exclusive end position of the error.
Parameter source
Source code of the broken file.
Parameter file
Absolute path to the broken file.
Parameter plugin
PostCSS plugin name, if error came from plugin.
property column
column?: number;
Source column of the error.
error.column //=> 1error.input.column //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.column
.
property endColumn
endColumn?: number;
Source column of the error's end, exclusive. Provided if the error pertains to a range.
error.endColumn //=> 1error.input.endColumn //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.endColumn
.
property endLine
endLine?: number;
Source line of the error's end, exclusive. Provided if the error pertains to a range.
error.endLine //=> 3error.input.endLine //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.endLine
.
property file
file?: string;
Absolute path to the broken file.
error.file //=> 'a.sass'error.input.file //=> 'a.css'PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.file
.
property input
input?: FilePosition;
Input object with PostCSS internal information about input file. If input has source map from previous tool, PostCSS will use origin (for example, Sass) source. You can use this object to get PostCSS input source.
error.input.file //=> 'a.css'error.file //=> 'a.sass'
property line
line?: number;
Source line of the error.
error.line //=> 2error.input.line //=> 4PostCSS will use the input source map to detect the original location. If you need the position in the PostCSS input, use
error.input.line
.
property message
message: string;
Full error text in the GNU error format with plugin, file, line and column.
error.message //=> 'a.css:1:1: Unclosed block'
property name
name: string;
Always equal to
'CssSyntaxError'
. You should always check error type byerror.name === 'CssSyntaxError'
instead oferror instanceof CssSyntaxError
, because npm could have several PostCSS versions.if (error.name === 'CssSyntaxError') {error //=> CssSyntaxError}
property plugin
plugin?: string;
Plugin name, if error came from plugin.
error.plugin //=> 'postcss-vars'
property reason
reason: string;
Error message.
error.message //=> 'Unclosed block'
property source
source?: string;
Source code of the broken file.
error.source //=> 'a { b {} }'error.input.source //=> 'a b { }'
property stack
stack: string;
method showSourceCode
showSourceCode: (color?: boolean) => string;
Returns a few lines of CSS source that caused the error.
If the CSS has an input source map without
sourceContent
, this method will return an empty string.error.showSourceCode() //=> " 4 | }// 5 | a {// > 6 | bad// | ^// 7 | }// 8 | b {"Parameter color
Whether arrow will be colored red by terminal color codes. By default, PostCSS will detect color support by
process.stdout.isTTY
andprocess.env.NODE_DISABLE_COLORS
. Few lines of CSS source that caused the error.
method toString
toString: () => string;
Returns error position, message and source code of the broken part.
error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block// > 1 | a {// | ^"Error position, message and source code.
class Declaration
class Declaration_ extends Node {}
It represents a class that handles [CSS declarations](https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_declarations)
Once (root, { Declaration }) {const color = new Declaration({ prop: 'color', value: 'black' })root.append(color)}const root = postcss.parse('a { color: black }')const decl = root.first?.firstdecl.type //=> 'decl'decl.toString() //=> ' color: black'
constructor
constructor(defaults?: Declaration.DeclarationProps);
property important
important: boolean;
It represents a specificity of the declaration.
If true, the CSS declaration will have an [important](https://developer.mozilla.org/en-US/docs/Web/CSS/important) specifier.
const root = postcss.parse('a { color: black !important; color: red }')root.first.first.important //=> trueroot.first.last.important //=> undefined
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property prop
prop: string;
The property name for a CSS declaration.
const root = postcss.parse('a { color: black }')const decl = root.first.firstdecl.prop //=> 'color'
property raws
raws: Declaration.DeclarationRaws;
property type
type: string;
property value
value: string;
The property value for a CSS declaration.
Any CSS comments inside the value string will be filtered out. CSS comments present in the source value will be available in the
raws
property.Assigning new
value
would ignore the comments inraws
property while compiling node to string.const root = postcss.parse('a { color: black }')const decl = root.first.firstdecl.value //=> 'black'
property variable
readonly variable: boolean;
It represents a getter that returns
true
if a declaration starts with--
or$
, which are used to declare variables in CSS and SASS/SCSS.const root = postcss.parse(':root { --one: 1 }')const one = root.first.firstone.variable //=> trueconst root = postcss.parse('$one: 1')const one = root.firstone.variable //=> true
method assign
assign: (overrides: Declaration.DeclarationProps | object) => this;
method clone
clone: (overrides?: Partial<Declaration.DeclarationProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Declaration.DeclarationProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Declaration.DeclarationProps>) => this;
class Document
class Document_ extends Container<Root> {}
Represents a file and contains all its parsed nodes.
**Experimental:** some aspects of this node could change within minor or patch version releases.
const document = htmlParser('<html><style>a{color:black}</style><style>b{z-index:2}</style>')document.type //=> 'document'document.nodes.length //=> 2
constructor
constructor(defaults?: Document.DocumentProps);
property nodes
nodes: Root[];
property parent
parent: undefined;
property type
type: string;
method assign
assign: (overrides: Document.DocumentProps | object) => this;
method clone
clone: (overrides?: Partial<Document.DocumentProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Document.DocumentProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Document.DocumentProps>) => this;
method toResult
toResult: (options?: ProcessOptions) => Result;
Returns a
Result
instance representing the document’s CSS roots.const root1 = postcss.parse(css1, { from: 'a.css' })const root2 = postcss.parse(css2, { from: 'b.css' })const document = postcss.document()document.append(root1)document.append(root2)const result = document.toResult({ to: 'all.css', map: true })Parameter opts
Options. Result with current document’s CSS.
class Input
class Input_ {}
Represents the source CSS.
const root = postcss.parse(css, { from: file })const input = root.source.input
constructor
constructor(css: string, opts?: ProcessOptions<Document_ | Root_>);
Parameter css
Input CSS source.
Parameter opts
Process options.
property css
css: string;
Input CSS source.
const input = postcss.parse('a{}', { from: file }).inputinput.css //=> "a{}"
property file
file?: string;
The absolute path to the CSS source file defined with the
from
option.const root = postcss.parse(css, { from: 'a.css' })root.source.input.file //=> '/home/ai/a.css'
property from
readonly from: string;
The CSS source identifier. Contains
Input#file
if the user set thefrom
option, orInput#id
if they did not.const root = postcss.parse(css, { from: 'a.css' })root.source.input.from //=> "/home/ai/a.css"const root = postcss.parse(css)root.source.input.from //=> "<input css 1>"
property hasBOM
hasBOM: boolean;
The flag to indicate whether or not the source code has Unicode BOM.
property id
id?: string;
The unique ID of the CSS source. It will be created if
from
option is not provided (because PostCSS does not know the file path).const root = postcss.parse(css)root.source.input.file //=> undefinedroot.source.input.id //=> "<input css 8LZeVF>"
property map
map: PreviousMap;
The input source map passed from a compilation step before PostCSS (for example, from Sass compiler).
root.source.input.map.consumer().sources //=> ['a.sass']
method error
error: { ( message: string, start: { column: number; line: number } | { offset: number }, end: { column: number; line: number } | { offset: number }, opts?: { plugin?: CssSyntaxError['plugin'] } ): CssSyntaxError; ( message: string, line: number, column: number, opts?: { plugin?: string } ): CssSyntaxError; ( message: string, offset: number, opts?: { plugin?: string } ): CssSyntaxError;};
Returns
CssSyntaxError
with information about the error and its position.
method fromOffset
fromOffset: (offset: number) => { col: number; line: number } | null;
Converts source offset to line and column.
Parameter offset
Source offset.
method origin
origin: ( line: number, column: number, endLine?: number, endColumn?: number) => false | Input.FilePosition;
Reads the input source map and returns a symbol position in the input source (e.g., in a Sass file that was compiled to CSS before being passed to PostCSS). Optionally takes an end position, exclusive.
root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }root.source.input.origin(1, 1, 1, 4)//=> { file: 'a.css', line: 3, column: 1, endLine: 3, endColumn: 4 }Parameter line
Line for inclusive start position in input CSS.
Parameter column
Column for inclusive start position in input CSS.
Parameter endLine
Line for exclusive end position in input CSS.
Parameter endColumn
Column for exclusive end position in input CSS.
Position in input source.
method toJSON
toJSON: () => object;
Converts this to a JSON-friendly object representation.
class LazyResult
class LazyResult_<RootNode = Document | Root> implements PromiseLike<Result<RootNode>> {}
A Promise proxy for the result of PostCSS transformations.
A
LazyResult
instance is returned byProcessor#process
.const lazy = postcss([autoprefixer]).process(css)
constructor
constructor(processor: Processor, css: string, opts: ResultOptions);
Parameter processor
Processor used for this transformation.
Parameter css
CSS to parse and transform.
Parameter opts
Options from the
Processor#process
orRoot#toResult
.
property [Symbol.toStringTag]
readonly [Symbol.toStringTag]: string;
Returns the default string description of an object. Required to implement the Promise interface.
property catch
catch: <TResult = never>( onrejected?: (reason: any) => TResult | PromiseLike<TResult>) => Promise<Result<RootNode> | TResult>;
Processes input CSS through synchronous and asynchronous plugins and calls onRejected for each error thrown in any plugin.
It implements standard Promise API.
postcss([autoprefixer]).process(css).then(result => {console.log(result.css)}).catch(error => {console.error(error)})
property content
readonly content: string;
An alias for the
css
property. Use it with syntaxes that generate non-CSS output.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property css
readonly css: string;
Processes input CSS through synchronous plugins, converts
Root
to a CSS string and returnsResult#css
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property finally
finally: (onfinally?: () => void) => Promise<Result<RootNode>>;
Processes input CSS through synchronous and asynchronous plugins and calls onFinally on any error or when all plugins will finish work.
It implements standard Promise API.
postcss([autoprefixer]).process(css).finally(() => {console.log('processing ended')})
property map
readonly map: any;
Processes input CSS through synchronous plugins and returns
Result#map
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property messages
readonly messages: Message[];
Processes input CSS through synchronous plugins and returns
Result#messages
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property opts
readonly opts: ResultOptions;
Options from the
Processor#process
call.
property processor
readonly processor: Processor;
Returns a
Processor
instance, which will be used for CSS transformations.
property root
readonly root: {};
Processes input CSS through synchronous plugins and returns
Result#root
.This property will only work with synchronous plugins. If the processor contains any asynchronous plugins it will throw an error.
PostCSS runners should always use
LazyResult#then
.
property then
then: <TResult1 = Result<RootNode>, TResult2 = never>( onfulfilled?: (value: Result<RootNode>) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<TResult1 | TResult2>;
Processes input CSS through synchronous and asynchronous plugins and calls
onFulfilled
with a Result instance. If a plugin throws an error, theonRejected
callback will be executed.It implements standard Promise API.
postcss([autoprefixer]).process(css, { from: cssPath }).then(result => {console.log(result.css)})
method async
async: () => Promise<Result<RootNode>>;
Run plugin in async way and return
Result
.Result with output content.
method sync
sync: () => Result<RootNode>;
Run plugin in sync way and return
Result
.Result with output content.
method toString
toString: () => string;
Alias for the
LazyResult#css
property.lazy + '' === lazy.cssOutput CSS.
method warnings
warnings: () => Warning[];
Processes input CSS through synchronous plugins and calls
Result#warnings
.Warnings from plugins.
class Node
class Node extends Node_ {}
class Processor
class Processor_ {}
Contains plugins to process CSS. Create one
Processor
instance, initialize its plugins, and then use that instance on numerous CSS files.const processor = postcss([autoprefixer, postcssNested])processor.process(css1).then(result => console.log(result.css))processor.process(css2).then(result => console.log(result.css))
constructor
constructor(plugins?: readonly AcceptedPlugin[]);
Parameter plugins
PostCSS plugins
property plugins
plugins: (Plugin | TransformCallback | Transformer)[];
Plugins added to this processor.
const processor = postcss([autoprefixer, postcssNested])processor.plugins.length //=> 2
property version
version: string;
Current PostCSS version.
if (result.processor.version.split('.')[0] !== '6') {throw new Error('This plugin works only with PostCSS 6')}
method process
process: { (css: { toString(): string } | LazyResult | Result | Root | string): | LazyResult | NoWorkResult; <RootNode extends Document | Root = Root>( css: | string | Root | Result<Document | Root> | LazyResult<Document | Root> | { toString(): string }, options: ProcessOptions<RootNode> ): LazyResult<RootNode>;};
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 theLazyResult
methods.processor.process(css, { from: 'a.css', to: 'a.out.css' }).then(result => {console.log(result.css)})Parameter css
String with input CSS or any object with a
toString()
method, like a Buffer. Optionally, send aResult
instance and the processor will take theRoot
from it.Parameter opts
Options. Promise proxy.
method use
use: (plugin: AcceptedPlugin) => this;
Adds a plugin to be used as a CSS processor.
PostCSS plugin can be in 4 formats: * A plugin in
Plugin
format. * A plugin creator function withpluginCreator.postcss = true
. PostCSS will call this function without argument to get plugin. * A function. PostCSS will pass the function a Root as the first argument and currentResult
instance as the second. * AnotherProcessor
instance. PostCSS will copy plugins from that instance into this one.Plugins can also be added by passing them as arguments when creating a
postcss
instance (see [postcss(plugins)
]).Asynchronous plugins should return a
Promise
instance.const processor = postcss().use(autoprefixer).use(postcssNested)Parameter plugin
PostCSS plugin or
Processor
with plugins. Current processor to make methods chain.
class Result
class Result_<RootNode = Document | Root> {}
Provides the result of the PostCSS transformations.
A Result instance is returned by
LazyResult#then
orRoot#toResult
methods.postcss([autoprefixer]).process(css).then(result => {console.log(result.css)})const result2 = postcss.parse(css).toResult()
constructor
constructor(processor: Processor, root: {}, opts: Result.ResultOptions);
Parameter processor
Processor used for this transformation.
Parameter root
Root node after all transformations.
Parameter opts
Options from the
Processor#process
orRoot#toResult
.
property content
readonly content: string;
An alias for the
Result#css
property. Use it with syntaxes that generate non-CSS output.result.css === result.content
property css
css: string;
A CSS string representing of
Result#root
.postcss.parse('a{}').toResult().css //=> "a{}"
property lastPlugin
lastPlugin: Plugin | TransformCallback;
Last runned PostCSS plugin.
property map
map: any;
An instance of
SourceMapGenerator
class from thesource-map
library, representing changes to theResult#root
instance.result.map.toJSON() //=> { version: 3, file: 'a.css', … }if (result.map) {fs.writeFileSync(result.opts.to + '.map', result.map.toString())}
property messages
messages: Result.Message[];
Contains messages from plugins (e.g., warnings or custom messages). Each message should have type and plugin properties.
AtRule: {import: (atRule, { result }) {const importedFile = parseImport(atRule)result.messages.push({type: 'dependency',plugin: 'postcss-import',file: importedFile,parent: result.opts.from})}}
property opts
opts: Result.ResultOptions;
Options from the
Processor#process
orRoot#toResult
call that produced this Result instance.]root.toResult(opts).opts === opts
property processor
processor: Processor;
The Processor instance used for this transformation.
for (const plugin of result.processor.plugins) {if (plugin.postcssPlugin === 'postcss-bad') {throw 'postcss-good is incompatible with postcss-bad'}})
property root
root: {};
Root node after all transformations.
root.toResult().root === root
method toString
toString: () => string;
Returns for
Result#css
content.result + '' === result.cssString representing of
Result#root
.
method warn
warn: (message: string, options?: WarningOptions) => Warning;
Creates an instance of
Warning
and adds it toResult#messages
.if (decl.important) {result.warn('Avoid !important', { node: decl, word: '!important' })}Parameter text
Warning message.
Parameter opts
Warning options. Created warning.
method warnings
warnings: () => Warning[];
Returns warnings from plugins. Filters
Warning
instances fromResult#messages
.result.warnings().forEach(warn => {console.warn(warn.toString())})Warnings from plugins.
class Root
class Root_ extends Container {}
Represents a CSS file and contains all its parsed nodes.
const root = postcss.parse('a{color:black} b{z-index:2}')root.type //=> 'root'root.nodes.length //=> 2
constructor
constructor(defaults?: Root.RootProps);
property nodes
nodes: Node.ChildNode[];
property parent
parent: Document;
property raws
raws: Root.RootRaws;
property type
type: string;
method assign
assign: (overrides: object | Root.RootProps) => this;
method clone
clone: (overrides?: Partial<Root.RootProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Root.RootProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Root.RootProps>) => this;
method toResult
toResult: (options?: ProcessOptions) => Result;
Returns a
Result
instance representing the root’s CSS.const root1 = postcss.parse(css1, { from: 'a.css' })const root2 = postcss.parse(css2, { from: 'b.css' })root1.append(root2)const result = root1.toResult({ to: 'all.css', map: true })Parameter options
Options. Result with current root’s CSS.
class Rule
class Rule_ extends Container {}
Represents a CSS rule: a selector followed by a declaration block.
Once (root, { Rule }) {let a = new Rule({ selector: 'a' })a.append(…)root.append(a)}const root = postcss.parse('a{}')const rule = root.firstrule.type //=> 'rule'rule.toString() //=> 'a{}'
constructor
constructor(defaults?: Rule.RuleProps);
property nodes
nodes: Node.ChildNode[];
property parent
parent: ContainerWithChildren<Node.ChildNode>;
property raws
raws: Rule.RuleRaws;
property selector
selector: string;
The rule’s full selector represented as a string.
const root = postcss.parse('a, b { }')const rule = root.firstrule.selector //=> 'a, b'
property selectors
selectors: string[];
An array containing the rule’s individual selectors. Groups of selectors are split at commas.
const root = postcss.parse('a, b { }')const rule = root.firstrule.selector //=> 'a, b'rule.selectors //=> ['a', 'b']rule.selectors = ['a', 'strong']rule.selector //=> 'a, strong'
property type
type: string;
method assign
assign: (overrides: object | Rule.RuleProps) => this;
method clone
clone: (overrides?: Partial<Rule.RuleProps>) => this;
method cloneAfter
cloneAfter: (overrides?: Partial<Rule.RuleProps>) => this;
method cloneBefore
cloneBefore: (overrides?: Partial<Rule.RuleProps>) => this;
class Warning
class Warning_ {}
Represents a plugin’s warning. It can be created using
Node#warn
.if (decl.important) {decl.warn(result, 'Avoid !important', { word: '!important' })}
constructor
constructor(text: string, opts?: Warning.WarningOptions);
Parameter text
Warning message.
Parameter opts
Warning options.
property column
column: number;
Column for inclusive start position in the input file with this warning’s source.
warning.column //=> 6
property endColumn
endColumn?: number;
Column for exclusive end position in the input file with this warning’s source.
warning.endColumn //=> 4
property endLine
endLine?: number;
Line for exclusive end position in the input file with this warning’s source.
warning.endLine //=> 6
property line
line: number;
Line for inclusive start position in the input file with this warning’s source.
warning.line //=> 5
property node
node: Node;
Contains the CSS node that caused the warning.
warning.node.toString() //=> 'color: white !important'
property plugin
plugin: string;
The name of the plugin that created this warning. When you call
Node#warn
it will fill this property automatically.warning.plugin //=> 'postcss-important'
property text
text: string;
The warning message.
warning.text //=> 'Try to avoid !important'
property type
type: string;
Type to filter warnings from
Result#messages
. Always equal to"warning"
.
method toString
toString: () => string;
Returns a warning position and message.
warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'Warning position and message.
interface AtRuleProps
interface AtRuleProps extends ContainerProps {}
interface Builder
interface Builder {}
call signature
(part: string, node?: AnyNode, type?: 'end' | 'start'): void;
interface CommentProps
interface CommentProps extends NodeProps {}
interface ContainerProps
interface ContainerProps extends NodeProps {}
property nodes
nodes?: readonly (ChildProps | Node)[];
interface DeclarationProps
interface DeclarationProps {}
property important
important?: boolean;
Whether the declaration has an
!important
annotation.
property prop
prop: string;
Name of the declaration.
property raws
raws?: DeclarationRaws;
Information used to generate byte-to-byte equal node string as it was in the origin input.
property value
value: string;
Value of the declaration.
interface DocumentProps
interface DocumentProps extends ContainerProps {}
interface FilePosition
interface FilePosition {}
property column
column: number;
Column of inclusive start position in source file.
property endColumn
endColumn?: number;
Column of exclusive end position in source file.
property endLine
endLine?: number;
Line of exclusive end position in source file.
property file
file?: string;
Absolute path to the source file.
property line
line: number;
Line of inclusive start position in source file.
property source
source?: string;
Source code.
property url
url: string;
URL for the source file.
interface JSONHydrator
interface JSONHydrator {}
call signature
(data: object): Node;
call signature
(data: object[]): Node[];
interface Message
interface Message {}
property plugin
plugin?: string;
Source PostCSS plugin name.
property type
type: string;
Message type.
index signature
[others: string]: any;
interface NodeErrorOptions
interface NodeErrorOptions {}
property endIndex
endIndex?: number;
An ending index inside a node's string that should be highlighted as source of error.
property index
index?: number;
An index inside a node's string that should be highlighted as source of error.
property plugin
plugin?: string;
Plugin name that created this error. PostCSS will set it automatically.
property word
word?: string;
A word inside a node's string, that should be highlighted as source of error.
interface NodeProps
interface NodeProps {}
Interface represents an interface for an object received as parameter by Node class constructor.
property source
source?: Source;
interface OldPlugin
interface OldPlugin<T> extends Transformer {}
property postcss
postcss: Transformer;
call signature
(opts?: T): Transformer;
interface Parser
interface Parser<RootNode = Document | Root> {}
call signature
( css: { toString(): string } | string, opts?: Pick<ProcessOptions, 'from' | 'map'>): RootNode;
interface Plugin
interface Plugin extends Processors {}
property postcssPlugin
postcssPlugin: string;
property prepare
prepare?: (result: Result) => Processors;
interface PluginCreator
interface PluginCreator<PluginOptions> {}
property postcss
postcss: true;
call signature
(opts?: PluginOptions): Plugin | Processor;
interface Position
interface Position {}
interface ProcessOptions
interface ProcessOptions<RootNode = Document | Root> {}
property from
from?: string | undefined;
The path of the CSS source file. You should always set
from
, because it is used in source map generation and syntax error messages.
property map
map?: boolean | SourceMapOptions;
Source map options
property parser
parser?: Parser<RootNode> | Syntax<RootNode>;
Function to generate AST by string.
property stringifier
stringifier?: Stringifier | Syntax<RootNode>;
Class to generate string by AST.
property syntax
syntax?: Syntax<RootNode>;
Object with parse and stringify.
property to
to?: string;
The path where you'll put the output CSS file. You should always set
to
to generate correct source maps.
interface RootProps
interface RootProps extends ContainerProps {}
property raws
raws?: RootRaws;
Information used to generate byte-to-byte equal node string as it was in the origin input.
interface Source
interface Source {}
Source represents an interface for the Node.source property.
interface SourceMapOptions
interface SourceMapOptions {}
property absolute
absolute?: boolean;
Use absolute path in generated source map.
property annotation
annotation?: ((file: string, root: Root) => string) | boolean | string;
Indicates that PostCSS should add annotation comments to the CSS. By default, PostCSS will always add a comment with a path to the source map. PostCSS will not add annotations to CSS files that do not contain any comments.
By default, PostCSS presumes that you want to save the source map as
opts.to + '.map'
and will use this path in the annotation comment. A different path can be set by providing a string value for annotation.If you have set
inline: true
, annotation cannot be disabled.
property from
from?: string;
Override
from
in map’s sources.
property inline
inline?: boolean;
Indicates that the source map should be embedded in the output CSS as a Base64-encoded comment. By default, it is
true
. But if all previous maps are external, not inline, PostCSS will not embed the map even if you do not set this option.If you have an inline source map, the result.map property will be empty, as the source map will be contained within the text of
result.css
.
property prev
prev?: ((file: string) => string) | boolean | object | string;
Source map content from a previous processing step (e.g., Sass).
PostCSS will try to read the previous source map automatically (based on comments within the source CSS), but you can use this option to identify it manually.
If desired, you can omit the previous map with prev:
false
.
property sourcesContent
sourcesContent?: boolean;
Indicates that PostCSS should set the origin content (e.g., Sass source) of the source map. By default, it is true. But if all previous maps do not contain sources content, PostCSS will also leave it out even if you do not set this option.
interface Stringifier
interface Stringifier {}
call signature
(node: AnyNode, builder: Builder): void;
interface Syntax
interface Syntax<RootNode = Document | Root> {}
interface TransformCallback
interface TransformCallback {}
call signature
(root: Root, result: Result): Promise<void> | void;
interface Transformer
interface Transformer extends TransformCallback {}
property postcssPlugin
postcssPlugin: string;
property postcssVersion
postcssVersion: string;
interface WarningOptions
interface WarningOptions {}
property end
end?: RangePosition;
End position, exclusive, in CSS node string that caused the warning.
property endIndex
endIndex?: number;
End index, exclusive, in CSS node string that caused the warning.
property index
index?: number;
Start index, inclusive, in CSS node string that caused the warning.
property node
node?: Node;
CSS node that caused the warning.
property plugin
plugin?: string;
Name of the plugin that created this warning.
Result#warn
fills this property automatically.
property start
start?: RangePosition;
Start position, inclusive, in CSS node string that caused the warning.
property word
word?: string;
Word in CSS source that caused the warning.
type AcceptedPlugin
type AcceptedPlugin = | { postcss: Processor | TransformCallback; } | OldPlugin<any> | Plugin | PluginCreator<any> | Processor | TransformCallback;
type AnyNode
type AnyNode = AtRule.default | Comment | Declaration | Document | Root | Rule;
type ChildNode
type ChildNode = AtRule.default | Comment | Declaration | Rule;
type ChildProps
type ChildProps = AtRuleProps | CommentProps | DeclarationProps | RuleProps;
type Helpers
type Helpers = { postcss: Postcss; result: Result } & Postcss;
type NewChild
type NewChild = | ChildProps | Node | readonly ChildProps[] | readonly Node[] | readonly string[] | string | undefined;
All types that can be passed into container methods to create or add a new child node.
type Postcss
type Postcss = typeof postcss;
type RuleProps
type RuleProps = { /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ raws?: RuleRaws;} & ( | { /** Selector or selectors of the rule. */ selector: string; selectors?: never; } | { selector?: never; /** Selectors of the rule represented as an array of strings. */ selectors: readonly string[]; }) & ContainerProps;
type SourceMap
type SourceMap = { toJSON(): RawSourceMap;} & SourceMapGenerator;
Package Files (15)
Dependencies (3)
Dev Dependencies (0)
No dev dependencies.
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/postcss
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/postcss)
- HTML<a href="https://www.jsdocs.io/package/postcss"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 12427 ms. - Missing or incorrect documentation? Open an issue for this package.