postcss

创建一个新的Processor实例,它将应用plugins作为 CSS 处理器。

let postcss = require('postcss')

postcss(plugins).process(css, { from, to }).then(result => {
  console.log(result.css)
})
参数类型描述
插件AcceptedPlugin[]PostCSS 插件。
参数类型描述
plugins…AcceptedPlugin[]PostCSS 插件。

返回 Processor

postcss.AcceptedPlugin

类型:Object | OldPlugin<any> | Plugin | PluginCreator<any> | Processor | TransformCallback

postcss.Builder

参数类型
partstring
nodeAnyNode
type"end" | "start"

postcss.Helpers

类型:Object & Postcss

postcss.JSONHydrator

参数类型
dataobject
参数类型
dataobject[]

返回 Node

postcss.OldPlugin

参数类型
optsT
参数类型
rootRoot
resultResult<Document_ | Root>

返回 Transformer

postcss.Parser

参数类型
cssstring | Object
optsPick<ProcessOptions<Document_ | Root>, "map" | "from">

返回 RootNode

postcss.PluginCreator

参数类型
optsPluginOptions

返回 Processor | Plugin

postcss.Postcss

类型:typeof postcss。

postcss.SourceMap

类型:SourceMapGenerator & Object。

postcss.Stringifier

参数类型
nodeAnyNode
builderBuilder

postcss.TransformCallback

参数类型
rootRoot
resultResult<Document_ | Root>

返回 void | Promise<void>

postcss.Transformer

参数类型
rootRoot
resultResult<Document_ | Root>

返回 void | Promise<void>

postcss.atRule

创建一个新的 AtRule 节点。

参数类型描述
defaultsAtRuleProps新节点的属性。

返回 AtRule_

postcss.comment

创建一个新的 Comment 节点。

参数类型描述
defaultsCommentProps新节点的属性。

返回 Comment_

postcss.decl

创建一个新的 Declaration 节点。

参数类型描述
defaultsDeclarationProps新节点的属性。

返回 Declaration_

postcss.document

创建一个新的 Document 节点。

参数类型描述
defaultsDocumentProps新节点的属性。

返回 Document_

postcss.fromJSON

将 JSON AST(来自 Node#toJSON)重新注入 AST 类。

const json = root.toJSON()
// save to file, send by network, etc
const root2  = postcss.fromJSON(json)
参数类型
dataobject
参数类型
dataobject[]

返回 Node

postcss.list

类型:List

postcss.parse

解析源 CSS 并返回一个新的 RootDocument 节点,其中包含源 CSS 节点。

// Simple CSS concatenation with source map support
const root1 = postcss.parse(css1, { from: file1 })
const root2 = postcss.parse(css2, { from: file2 })
root1.append(root2).toResult().css
参数类型
cssstring | Object
optsPick<ProcessOptions<Document_ | Root>, "map" | "from">

返回 Root

postcss.root

创建一个新的 Root 节点。

参数类型描述
defaultsRootProps新节点的属性。

返回 Root

postcss.rule

创建一个新的 Rule 节点。

参数类型
defaultsRuleProps

返回 Rule

postcss.stringify

将节点树转换为 CSS 字符串的默认函数。

参数类型
nodeAnyNode
builderBuilder

AtRule

表示一个 at 规则。

Once (root, { AtRule }) {
  let media = new AtRule({ name: 'media', params: 'print' })
  media.append(…)
  root.append(media)
}

如果 CSS 中后面跟着一个 {} 块,则此节点将具有一个表示其子节点的 nodes 属性。

const root = postcss.parse('@charset "UTF-8"; @media print {}')

const charset = root.first
charset.type  //=> 'atrule'
charset.nodes //=> undefined

const media = root.last
media.nodes   //=> []

AtRule#after()

在当前节点的父节点中将新节点插入到当前节点之后。

只是 node.parent.insertAfter(node, add) 的别名。

decl.after('color: black')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 AtRule

AtRule#append()

将新节点插入到容器的末尾。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.append(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 AtRule

AtRule#assign()

它将属性分配给现有的节点实例。

decl.assign({ prop: 'word-wrap', value: 'break-word' })
参数类型描述
overridesobject | AtRuleProps要覆盖节点的新属性。

返回 AtRule

AtRule#before()

在当前节点的父节点中将新节点插入到当前节点之前。

只是 node.parent.insertBefore(node, add) 的别名。

decl.before('content: ""')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 AtRule

AtRule#cleanRaws()

清除节点及其子节点的代码样式属性。

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
参数类型描述
keepBetweenboolean保留 raws.between 符号。

AtRule#clone()

它创建现有节点的克隆,其中包括所有属性及其值,包括 raws 但不包括 type

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
参数类型描述
overridesPartial<AtRuleProps>在克隆中要覆盖的新属性。

返回 AtRule

AtRule#cloneAfter()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之后。

参数类型描述
overridesPartial<AtRuleProps>在克隆中要覆盖的新属性。

返回 AtRule

AtRule#cloneBefore()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之前。

decl.cloneBefore({ prop: '-moz-' + decl.prop })
参数类型描述
overridesPartial<AtRuleProps>要在克隆中覆盖的新属性。

返回 AtRule

AtRule#each()

遍历容器的直接子项,为每个子项调用callback

在回调中返回false将中断迭代。

此方法仅遍历容器的直接子项。如果您需要递归遍历容器的所有后代节点,请使用Container#walk

与 for {}-cycle 或 Array#forEach 不同,如果您在迭代期间改变子节点数组,此迭代器是安全的。PostCSS 将调整当前索引以匹配更改。

const root = postcss.parse('a { color: black; z-index: 1 }')
const rule = root.first

for (const decl of rule.nodes) {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Cycle will be infinite, because cloneBefore moves the current node
  // to the next index
}

rule.each(decl => {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Will be executed only for color and z-index
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

AtRule#error()

它创建一个类CssSyntaxError的实例,并向此方法传递的参数分配给错误实例。

错误实例将具有错误描述、节点在源中的原始位置、显示行号和列号。

如果存在任何先前的映射,它将用于获取源的原始位置。

此处的先前映射是指由先前编译生成的源映射,例如:Less、Stylus 和 Sass。

此方法返回错误实例,而不是抛出它。

if (!variables[name]) {
  throw decl.error(`Unknown variable ${name}`, { word: name })
  // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  //   color: $black
  // a
  //          ^
  //   background: white
}
参数类型描述
messagestring错误实例的描述。
optionsNodeErrorOptions错误实例的选项。

返回CssSyntaxError_

AtRule#every()

如果回调对容器的所有子项返回true,则返回true

const noPrefixes = rule.every(i => i.prop[0] !== '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

AtRule#index()

返回childContainer#nodes数组中的索引。

rule.index( rule.nodes[2] ) //=> 2
参数类型描述
childnumber | ChildNode当前容器的子项。

返回number

AtRule#insertAfter()

在容器中将新节点插入旧节点之后。

参数类型描述
oldNodenumber | ChildNode子项或子项的索引。
newNodestring | string[] | ChildNode | ChildProps | ChildNode[] | ChildProps[]新节点。

返回 AtRule

AtRule#insertBefore()

在容器中将新节点插入到旧节点之前。

rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
参数类型描述
oldNodenumber | ChildNode子项或子项的索引。
newNodestring | string[] | ChildNode | ChildProps | ChildNode[] | ChildProps[]新节点。

返回 AtRule

AtRule#name

at 规则的名称紧跟在 @ 之后。

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

类型:字符串。

AtRule#next()

返回节点父级的下一个子级。如果当前节点是最后一个子级,则返回 undefined

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

返回 ChildNode

AtRule#nodes

包含容器子级的数组。

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

类型:ChildNode[].

AtRule#params

at 规则的参数,即 at 规则名称后面但位于任何 {} 块之前的那些值。

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

类型:字符串。

AtRule#parent

它表示当前节点的父级。

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

类型:Container_<ChildNode>。

AtRule#positionBy()

获取节点内部某个单词或索引的位置。

参数类型描述
optsPick<WarningOptions, "index" | "word">选项。

返回 Position

AtRule#positionInside()

将字符串索引转换为行/列。

参数类型描述
indexnumber节点字符串中的符号数。

返回 Position

AtRule#prepend()

在容器开头插入新节点。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.prepend(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 AtRule

AtRule#prev()

返回节点父级的上一个子级。如果当前节点是第一个子级,则返回 undefined

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

返回 ChildNode

AtRule#push()

在节点末尾添加子级。

rule.push(new Declaration({ prop: 'color', value: 'black' }))
参数类型描述
childChildNode新节点。

返回 AtRule

AtRule#rangeBy()

获取节点内部某个单词或起始和结束索引的范围。起始索引包含在内;结束索引不包含在内。

参数类型描述
optsPick<WarningOptions, "index" | "word" | "endIndex">选项。

返回 Range

AtRule#raw()

返回 raws 值。如果节点缺少代码样式属性(因为节点是手动构建或克隆的),PostCSS 将尝试通过查看树中的其他节点来自动检测代码样式属性。

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
参数类型描述
propstring代码样式属性的名称。
defaultTypestring默认值的名称,如果值与 prop 相同,则可以省略。

返回 string

AtRule#raws

它表示 css 源代码中存在的不必要的空格和字符。

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

raws 对象的属性由解析器决定,默认解析器使用以下属性

PostCSS 会过滤选择器、声明值和 at 规则参数中的注释,但它会将原始内容存储在 raws 中。

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

类型:AtRuleRaws

AtRule#remove()

它从其父级中移除节点并删除其父级属性。

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

返回 AtRule

AtRule#removeAll()

从容器中移除所有子节点并清除其父级属性。

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

返回 AtRule

AtRule#removeChild()

从容器中移除节点并清除节点及其子节点的父级属性。

rule.nodes.length  //=> 5
rule.removeChild(decl)
rule.nodes.length  //=> 4
decl.parent        //=> undefined
参数类型描述
childnumber | ChildNode子项或子项的索引。

返回 AtRule

AtRule#replaceValues()

参数类型
patternstring | RegExp
replacedstring | Function
参数类型描述
patternstring | RegExp替换模式。
optionsValueOptions
replacedstring | Function

返回 AtRule

AtRule#replaceWith()

在当前节点之前插入节点并移除当前节点。

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
参数类型描述
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]替换当前模式的模式。

返回 AtRule

AtRule#root()

查找节点树的 Root 实例。

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

返回 Root

AtRule#some()

如果回调对容器的(至少)一个子节点返回 true,则返回 true

const hasPrefix = rule.some(i => i.prop[0] === '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

AtRule#source

它表示与节点的来源相关的信息,并且是生成源映射所必需的。

使用 PostCSS 提供的公共 API 手动创建的节点将具有未定义的 source,并且在源映射中将不存在。

出于此原因,插件开发人员应考虑复制节点,因为默认情况下复制的节点将与原始节点具有相同的源,或将源分配给手动创建的节点。

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

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

 atrule.parent.insertBefore(atrule, rule)
}

类型:Source

AtRule#toJSON()

修复 JSON.stringify() 上的循环链接。

返回 object

AtRule#toString()

根据其类型将节点编译为浏览器可读的层叠样式表字符串。

new Rule({ selector: 'a' }).toString() //=> "a {}"
参数类型描述
stringifierStringifier | Syntax<Document_ | Root>在字符串生成中使用的语法。

返回 string

AtRule#type

它表示抽象语法树中节点的类型。

节点的类型有助于识别节点并根据其类型执行操作。

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

declaration.type //=> 'decl'

类型:“atrule”。

AtRule#walk()

遍历容器的后代节点,为每个节点调用回调。

与 container.each() 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

如果您只需要遍历容器的直接子项,请使用 Container#each

root.walk(node => {
  // Traverses all descendant nodes.
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

AtRule#walkAtRules()

遍历容器的后代节点,为每个 at-rule 节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配名称的 at-rule 上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

root.walkAtRules(rule => {
  if (isOld(rule.name)) rule.remove()
})

let first = false
root.walkAtRules('charset', rule => {
  if (!first) {
    first = true
  } else {
    rule.remove()
  }
})
参数类型描述
nameFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

AtRule#walkComments()

参数类型
callback函数

返回void | false

AtRule#walkDecls()

遍历容器的后代节点,为每个声明节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配属性的声明上。

root.walkDecls(decl => {
  checkPropertySupport(decl.prop)
})

root.walkDecls('border-radius', decl => {
  decl.remove()
})

root.walkDecls(/^background/, decl => {
  decl.value = takeFirstColorFromGradient(decl.value)
})

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

参数类型描述
propFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

AtRule#walkRules()

遍历容器的后代节点,为每个规则节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配选择器的规则上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

const selectors = []
root.walkRules(rule => {
  selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
参数类型描述
selectorFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

AtRule#warn()

它是 Result#warn 的包装器,提供了生成警告的便捷方式。

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
参数类型描述
resultResult<Document_ | Root>将接收警告的 Result 实例。
messagestring警告的描述。
optionsWarningOptions警告的选项。

返回 Warning

Comment

它表示一个处理 CSS 注释 的类

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

请记住,选择器、at-rule 参数或声明值中的 CSS 注释将存储在上面解释的 raws 属性中。

注释#after()

在当前节点的父节点中将新节点插入到当前节点之后。

只是 node.parent.insertAfter(node, add) 的别名。

decl.after('color: black')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回注释

注释#assign()

它将属性分配给现有的节点实例。

decl.assign({ prop: 'word-wrap', value: 'break-word' })
参数类型描述
overrides对象 | 注释属性要覆盖节点的新属性。

返回注释

注释#before()

在当前节点的父节点中将新节点插入到当前节点之前。

只是 node.parent.insertBefore(node, add) 的别名。

decl.before('content: ""')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回注释

注释#cleanRaws()

清除节点及其子节点的代码样式属性。

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
参数类型描述
keepBetweenboolean保留 raws.between 符号。

注释#clone()

它创建现有节点的克隆,其中包括所有属性及其值,包括 raws 但不包括 type

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
参数类型描述
overrides部分<注释属性>在克隆中要覆盖的新属性。

返回注释

注释#cloneAfter()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之后。

参数类型描述
overrides部分<注释属性>在克隆中要覆盖的新属性。

返回注释

注释#cloneBefore()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之前。

decl.cloneBefore({ prop: '-moz-' + decl.prop })
参数类型描述
overrides部分<注释属性>要在克隆中覆盖的新属性。

返回注释

注释#error()

它创建一个类CssSyntaxError的实例,并向此方法传递的参数分配给错误实例。

错误实例将具有错误描述、节点在源中的原始位置、显示行号和列号。

如果存在任何先前的映射,它将用于获取源的原始位置。

此处的先前映射是指由先前编译生成的源映射,例如:Less、Stylus 和 Sass。

此方法返回错误实例,而不是抛出它。

if (!variables[name]) {
  throw decl.error(`Unknown variable ${name}`, { word: name })
  // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  //   color: $black
  // a
  //          ^
  //   background: white
}
参数类型描述
messagestring错误实例的描述。
optionsNodeErrorOptions错误实例的选项。

返回CssSyntaxError_

注释#next()

返回节点父级的下一个子级。如果当前节点是最后一个子级,则返回 undefined

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

返回 ChildNode

注释#parent

它表示当前节点的父级。

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

类型:Container_<ChildNode>。

注释#positionBy()

获取节点内部某个单词或索引的位置。

参数类型描述
optsPick<WarningOptions, "index" | "word">选项。

返回 Position

注释#positionInside()

将字符串索引转换为行/列。

参数类型描述
indexnumber节点字符串中的符号数。

返回 Position

注释#prev()

返回节点父级的上一个子级。如果当前节点是第一个子级,则返回 undefined

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

返回 ChildNode

注释#rangeBy()

获取节点内部某个单词或起始和结束索引的范围。起始索引包含在内;结束索引不包含在内。

参数类型描述
optsPick<WarningOptions, "index" | "word" | "endIndex">选项。

返回 Range

注释#raw()

返回 raws 值。如果节点缺少代码样式属性(因为节点是手动构建或克隆的),PostCSS 将尝试通过查看树中的其他节点来自动检测代码样式属性。

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
参数类型描述
propstring代码样式属性的名称。
defaultTypestring默认值的名称,如果值与 prop 相同,则可以省略。

返回 string

注释#raws

它表示 css 源代码中存在的不必要的空格和字符。

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

raws 对象的属性由解析器决定,默认解析器使用以下属性

PostCSS 会过滤选择器、声明值和 at 规则参数中的注释,但它会将原始内容存储在 raws 中。

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

类型:注释 Raws

注释#remove()

它从其父级中移除节点并删除其父级属性。

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

返回注释

注释#replaceWith()

在当前节点之前插入节点并移除当前节点。

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
参数类型描述
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]替换当前模式的模式。

返回注释

注释#root()

查找节点树的 Root 实例。

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

返回 Root

注释#source

它表示与节点的来源相关的信息,并且是生成源映射所必需的。

使用 PostCSS 提供的公共 API 手动创建的节点将具有未定义的 source,并且在源映射中将不存在。

出于此原因,插件开发人员应考虑复制节点,因为默认情况下复制的节点将与原始节点具有相同的源,或将源分配给手动创建的节点。

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

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

 atrule.parent.insertBefore(atrule, rule)
}

类型:Source

注释#text

注释的文本。

类型:字符串。

注释#toJSON()

修复 JSON.stringify() 上的循环链接。

返回 object

注释#toString()

根据其类型将节点编译为浏览器可读的层叠样式表字符串。

new Rule({ selector: 'a' }).toString() //=> "a {}"
参数类型描述
stringifierStringifier | Syntax<Document_ | Root>在字符串生成中使用的语法。

返回 string

注释#type

它表示抽象语法树中节点的类型。

节点的类型有助于识别节点并根据其类型执行操作。

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

declaration.type //=> 'decl'

类型:“注释”。

注释#warn()

它是 Result#warn 的包装器,提供了生成警告的便捷方式。

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
参数类型描述
resultResult<Document_ | Root>将接收警告的 Result 实例。
messagestring警告的描述。
optionsWarningOptions警告的选项。

返回 Warning

容器

At 规则规则容器节点继承了一些常见方法,以帮助处理其子级。

请注意,所有容器都可以存储任何内容。如果在规则内编写规则,PostCSS 将对其进行解析。

容器#after()

在当前节点的父节点中将新节点插入到当前节点之后。

只是 node.parent.insertAfter(node, add) 的别名。

decl.after('color: black')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回容器<子级>

容器#append()

将新节点插入到容器的末尾。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.append(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回容器<子级>

容器#assign()

它将属性分配给现有的节点实例。

decl.assign({ prop: 'word-wrap', value: 'break-word' })
参数类型描述
overrides对象 | 容器属性要覆盖节点的新属性。

返回容器<子级>

容器#before()

在当前节点的父节点中将新节点插入到当前节点之前。

只是 node.parent.insertBefore(node, add) 的别名。

decl.before('content: ""')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回容器<子级>

容器#cleanRaws()

清除节点及其子节点的代码样式属性。

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
参数类型描述
keepBetweenboolean保留 raws.between 符号。

容器#clone()

它创建现有节点的克隆,其中包括所有属性及其值,包括 raws 但不包括 type

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
参数类型描述
overrides部分<容器属性>在克隆中要覆盖的新属性。

返回容器<子级>

容器#cloneAfter()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之后。

参数类型描述
overrides部分<容器属性>在克隆中要覆盖的新属性。

返回容器<子级>

容器#cloneBefore()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之前。

decl.cloneBefore({ prop: '-moz-' + decl.prop })
参数类型描述
overrides部分<容器属性>要在克隆中覆盖的新属性。

返回容器<子级>

容器#each()

遍历容器的直接子项,为每个子项调用callback

在回调中返回false将中断迭代。

此方法仅遍历容器的直接子项。如果您需要递归遍历容器的所有后代节点,请使用Container#walk

与 for {}-cycle 或 Array#forEach 不同,如果您在迭代期间改变子节点数组,此迭代器是安全的。PostCSS 将调整当前索引以匹配更改。

const root = postcss.parse('a { color: black; z-index: 1 }')
const rule = root.first

for (const decl of rule.nodes) {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Cycle will be infinite, because cloneBefore moves the current node
  // to the next index
}

rule.each(decl => {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Will be executed only for color and z-index
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

容器#error()

它创建一个类CssSyntaxError的实例,并向此方法传递的参数分配给错误实例。

错误实例将具有错误描述、节点在源中的原始位置、显示行号和列号。

如果存在任何先前的映射,它将用于获取源的原始位置。

此处的先前映射是指由先前编译生成的源映射,例如:Less、Stylus 和 Sass。

此方法返回错误实例,而不是抛出它。

if (!variables[name]) {
  throw decl.error(`Unknown variable ${name}`, { word: name })
  // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  //   color: $black
  // a
  //          ^
  //   background: white
}
参数类型描述
messagestring错误实例的描述。
optionsNodeErrorOptions错误实例的选项。

返回CssSyntaxError_

容器#every()

如果回调对容器的所有子项返回true,则返回true

const noPrefixes = rule.every(i => i.prop[0] !== '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

容器#index()

返回childContainer#nodes数组中的索引。

rule.index( rule.nodes[2] ) //=> 2
参数类型描述
child数字 | 子级当前容器的子项。

返回number

容器#insertAfter()

在容器中将新节点插入旧节点之后。

参数类型描述
oldNode数字 | 子级子项或子项的索引。
newNode字符串 | 字符串[] | 子级 | 子级属性 | 子级属性[] | 子级[]新节点。

返回容器<子级>

容器#insertBefore()

在容器中将新节点插入到旧节点之前。

rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
参数类型描述
oldNode数字 | 子级子项或子项的索引。
newNode字符串 | 字符串[] | 子级 | 子级属性 | 子级属性[] | 子级[]新节点。

返回容器<子级>

容器#next()

返回节点父级的下一个子级。如果当前节点是最后一个子级,则返回 undefined

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

返回 ChildNode

容器#nodes

包含容器子级的数组。

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

类型:子级[]。

容器#parent

它表示当前节点的父级。

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

类型:容器_<子节点> | 文档_。

容器#positionBy()

获取节点内部某个单词或索引的位置。

参数类型描述
optsPick<WarningOptions, "index" | "word">选项。

返回 Position

容器#positionInside()

将字符串索引转换为行/列。

参数类型描述
indexnumber节点字符串中的符号数。

返回 Position

容器#prepend()

在容器开头插入新节点。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.prepend(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回容器<子级>

容器#prev()

返回节点父级的上一个子级。如果当前节点是第一个子级,则返回 undefined

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

返回 ChildNode

容器#push()

在节点末尾添加子级。

rule.push(new Declaration({ prop: 'color', value: 'black' }))
参数类型描述
child子项新节点。

返回容器<子级>

容器#rangeBy()

获取节点内部某个单词或起始和结束索引的范围。起始索引包含在内;结束索引不包含在内。

参数类型描述
optsPick<WarningOptions, "index" | "word" | "endIndex">选项。

返回 Range

容器#raw()

返回 raws 值。如果节点缺少代码样式属性(因为节点是手动构建或克隆的),PostCSS 将尝试通过查看树中的其他节点来自动检测代码样式属性。

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
参数类型描述
propstring代码样式属性的名称。
defaultTypestring默认值的名称,如果值与 prop 相同,则可以省略。

返回 string

容器#raws

它表示 css 源代码中存在的不必要的空格和字符。

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

raws 对象的属性由解析器决定,默认解析器使用以下属性

PostCSS 会过滤选择器、声明值和 at 规则参数中的注释,但它会将原始内容存储在 raws 中。

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

类型:任意。

容器#remove()

它从其父级中移除节点并删除其父级属性。

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

返回容器<子级>

容器#removeAll()

从容器中移除所有子节点并清除其父级属性。

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

返回容器<子级>

容器#removeChild()

从容器中移除节点并清除节点及其子节点的父级属性。

rule.nodes.length  //=> 5
rule.removeChild(decl)
rule.nodes.length  //=> 4
decl.parent        //=> undefined
参数类型描述
child数字 | 子级子项或子项的索引。

返回容器<子级>

容器#replaceValues()

参数类型
patternstring | RegExp
replacedstring | Function
参数类型描述
patternstring | RegExp替换模式。
optionsValueOptions
replacedstring | Function

返回容器<子级>

容器#replaceWith()

在当前节点之前插入节点并移除当前节点。

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
参数类型描述
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]替换当前模式的模式。

返回容器<子级>

容器#root()

查找节点树的 Root 实例。

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

返回 Root

容器#some()

如果回调对容器的(至少)一个子节点返回 true,则返回 true

const hasPrefix = rule.some(i => i.prop[0] === '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

容器#source

它表示与节点的来源相关的信息,并且是生成源映射所必需的。

使用 PostCSS 提供的公共 API 手动创建的节点将具有未定义的 source,并且在源映射中将不存在。

出于此原因,插件开发人员应考虑复制节点,因为默认情况下复制的节点将与原始节点具有相同的源,或将源分配给手动创建的节点。

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

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

 atrule.parent.insertBefore(atrule, rule)
}

类型:Source

容器#toJSON()

修复 JSON.stringify() 上的循环链接。

返回 object

容器#toString()

根据其类型将节点编译为浏览器可读的层叠样式表字符串。

new Rule({ selector: 'a' }).toString() //=> "a {}"
参数类型描述
stringifierStringifier | Syntax<Document_ | Root>在字符串生成中使用的语法。

返回 string

容器#type

它表示抽象语法树中节点的类型。

节点的类型有助于识别节点并根据其类型执行操作。

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

declaration.type //=> 'decl'

类型:字符串。

容器#walk()

遍历容器的后代节点,为每个节点调用回调。

与 container.each() 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

如果您只需要遍历容器的直接子项,请使用 Container#each

root.walk(node => {
  // Traverses all descendant nodes.
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

容器#walkAtRules()

遍历容器的后代节点,为每个 at-rule 节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配名称的 at-rule 上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

root.walkAtRules(rule => {
  if (isOld(rule.name)) rule.remove()
})

let first = false
root.walkAtRules('charset', rule => {
  if (!first) {
    first = true
  } else {
    rule.remove()
  }
})
参数类型描述
nameFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

容器#walkComments()

参数类型
callback函数

返回void | false

容器#walkDecls()

遍历容器的后代节点,为每个声明节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配属性的声明上。

root.walkDecls(decl => {
  checkPropertySupport(decl.prop)
})

root.walkDecls('border-radius', decl => {
  decl.remove()
})

root.walkDecls(/^background/, decl => {
  decl.value = takeFirstColorFromGradient(decl.value)
})

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

参数类型描述
propFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

容器#walkRules()

遍历容器的后代节点,为每个规则节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配选择器的规则上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

const selectors = []
root.walkRules(rule => {
  selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
参数类型描述
selectorFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

容器#warn()

它是 Result#warn 的包装器,提供了生成警告的便捷方式。

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
参数类型描述
resultResult<Document_ | Root>将接收警告的 Result 实例。
messagestring警告的描述。
optionsWarningOptions警告的选项。

返回 Warning

CssSyntaxError

CSS 解析器会为损坏的 CSS 抛出此错误。

使用 节点#error 方法的自定义解析器会为损坏的自定义语法抛出此错误。

PostCSS 会使用输入源映射来检测原始错误位置。如果您编写了一个 Sass 文件,将其编译为 CSS,然后使用 PostCSS 解析它,PostCSS 会显示 Sass 文件中的原始位置。

如果您需要 PostCSS 输入中的位置(例如,调试之前的编译器),请使用 error.input.file

// Raising error from plugin
throw node.error('Unknown variable', { plugin: 'postcss-vars' })
// Catching and checking syntax error
try {
  postcss.parse('a{')
} catch (error) {
  if (error.name === 'CssSyntaxError') {
    error //=> CssSyntaxError
  }
}

CssSyntaxError#column

错误的源列。

error.column       //=> 1
error.input.column //=> 4

PostCSS 会使用输入源映射来检测原始位置。如果您需要 PostCSS 输入中的位置,请使用 error.input.column

类型:数字。

CssSyntaxError#endColumn

错误结束的源列(不包括)。如果错误涉及范围,则提供。

error.endColumn       //=> 1
error.input.endColumn //=> 4

PostCSS 会使用输入源映射来检测原始位置。如果您需要 PostCSS 输入中的位置,请使用 error.input.endColumn

类型:数字。

CssSyntaxError#endLine

错误结束的源行(不包括)。如果错误涉及范围,则提供。

error.endLine       //=> 3
error.input.endLine //=> 4

PostCSS 会使用输入源映射来检测原始位置。如果您需要 PostCSS 输入中的位置,请使用 error.input.endLine

类型:数字。

CssSyntaxError#file

损坏文件的绝对路径。

error.file       //=> 'a.sass'
error.input.file //=> 'a.css'

PostCSS 将使用输入源映射来检测原始位置。如果您需要 PostCSS 输入中的位置,请使用 error.input.file

类型:字符串。

CssSyntaxError#input

包含有关输入文件的 PostCSS 内部信息的输入对象。如果输入具有来自先前工具的源映射,PostCSS 将使用原始(例如,Sass)源。您可以使用此对象来获取 PostCSS 输入源。

error.input.file //=> 'a.css'
error.file       //=> 'a.sass'

类型:FilePosition

CssSyntaxError#line

错误的源行。

error.line       //=> 2
error.input.line //=> 4

PostCSS 将使用输入源映射来检测原始位置。如果您需要 PostCSS 输入中的位置,请使用 error.input.line

类型:数字。

CssSyntaxError#message

使用插件、文件、行和列的 GNU 错误格式的完整错误文本。

error.message //=> 'a.css:1:1: Unclosed block'

类型:字符串。

CssSyntaxError#name

始终等于 'CssSyntaxError'。您应始终通过 error.name === 'CssSyntaxError' 检查错误类型,而不是 error instanceof CssSyntaxError,因为 npm 可能有几个 PostCSS 版本。

if (error.name === 'CssSyntaxError') {
  error //=> CssSyntaxError
}

类型:"CssSyntaxError"。

CssSyntaxError#plugin

如果错误来自插件,则为插件名称。

error.plugin //=> 'postcss-vars'

类型:字符串。

CssSyntaxError#reason

错误消息。

error.message //=> 'Unclosed block'

类型:字符串。

CssSyntaxError#showSourceCode()

返回导致错误的几行 CSS 源。

如果 CSS 具有没有 sourceContent 的输入源映射,此方法将返回一个空字符串。

error.showSourceCode() //=> "  4 | }
                       //      5 | a {
                       //    > 6 |   bad
                       //        |   ^
                       //      7 | }
                       //      8 | b {"
参数类型描述
colorboolean箭头是否将由终端颜色代码着色为红色。默认情况下,PostCSS 将通过 process.stdout.isTTYprocess.env.NODE_DISABLE_COLORS 检测颜色支持。

返回 string

CssSyntaxError#source

损坏文件的源代码。

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

类型:字符串。

CssSyntaxError#stack

类型:字符串。

CssSyntaxError#toString()

返回损坏部分的错误位置、消息和源代码。

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

返回 string

Declaration

它表示一个处理CSS 声明的类。

Once (root, { Declaration }) {
  const color = new Declaration({ prop: 'color', value: 'black' })
  root.append(color)
}
const root = postcss.parse('a { color: black }')
const decl = root.first?.first

decl.type       //=> 'decl'
decl.toString() //=> ' color: black'

Declaration#after()

在当前节点的父节点中将新节点插入到当前节点之后。

只是 node.parent.insertAfter(node, add) 的别名。

decl.after('color: black')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Declaration

Declaration#assign()

它将属性分配给现有的节点实例。

decl.assign({ prop: 'word-wrap', value: 'break-word' })
参数类型描述
overridesobject | DeclarationProps要覆盖节点的新属性。

返回 Declaration

Declaration#before()

在当前节点的父节点中将新节点插入到当前节点之前。

只是 node.parent.insertBefore(node, add) 的别名。

decl.before('content: ""')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Declaration

Declaration#cleanRaws()

清除节点及其子节点的代码样式属性。

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
参数类型描述
keepBetweenboolean保留 raws.between 符号。

Declaration#clone()

它创建现有节点的克隆,其中包括所有属性及其值,包括 raws 但不包括 type

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
参数类型描述
overridesPartial<DeclarationProps>在克隆中要覆盖的新属性。

返回 Declaration

Declaration#cloneAfter()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之后。

参数类型描述
overridesPartial<DeclarationProps>在克隆中要覆盖的新属性。

返回 Declaration

Declaration#cloneBefore()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之前。

decl.cloneBefore({ prop: '-moz-' + decl.prop })
参数类型描述
overridesPartial<DeclarationProps>要在克隆中覆盖的新属性。

返回 Declaration

Declaration#error()

它创建一个类CssSyntaxError的实例,并向此方法传递的参数分配给错误实例。

错误实例将具有错误描述、节点在源中的原始位置、显示行号和列号。

如果存在任何先前的映射,它将用于获取源的原始位置。

此处的先前映射是指由先前编译生成的源映射,例如:Less、Stylus 和 Sass。

此方法返回错误实例,而不是抛出它。

if (!variables[name]) {
  throw decl.error(`Unknown variable ${name}`, { word: name })
  // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  //   color: $black
  // a
  //          ^
  //   background: white
}
参数类型描述
messagestring错误实例的描述。
optionsNodeErrorOptions错误实例的选项。

返回CssSyntaxError_

Declaration#important

它表示声明的特异性。

如果为真,CSS 声明将具有important说明符。

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

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

类型:布尔值。

声明#next()

返回节点父级的下一个子级。如果当前节点是最后一个子级,则返回 undefined

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

返回 ChildNode

声明#parent

它表示当前节点的父级。

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

类型:Container_<ChildNode>。

声明#positionBy()

获取节点内部某个单词或索引的位置。

参数类型描述
optsPick<WarningOptions, "index" | "word">选项。

返回 Position

声明#positionInside()

将字符串索引转换为行/列。

参数类型描述
indexnumber节点字符串中的符号数。

返回 Position

声明#prev()

返回节点父级的上一个子级。如果当前节点是第一个子级,则返回 undefined

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

返回 ChildNode

声明#prop

CSS 声明的属性名称。

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

decl.prop //=> 'color'

类型:字符串。

声明#rangeBy()

获取节点内部某个单词或起始和结束索引的范围。起始索引包含在内;结束索引不包含在内。

参数类型描述
optsPick<WarningOptions, "index" | "word" | "endIndex">选项。

返回 Range

声明#raw()

返回 raws 值。如果节点缺少代码样式属性(因为节点是手动构建或克隆的),PostCSS 将尝试通过查看树中的其他节点来自动检测代码样式属性。

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
参数类型描述
propstring代码样式属性的名称。
defaultTypestring默认值的名称,如果值与 prop 相同,则可以省略。

返回 string

声明#raws

它表示 css 源代码中存在的不必要的空格和字符。

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

raws 对象的属性由解析器决定,默认解析器使用以下属性

PostCSS 会过滤选择器、声明值和 at 规则参数中的注释,但它会将原始内容存储在 raws 中。

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

类型:DeclarationRaws

声明#remove()

它从其父级中移除节点并删除其父级属性。

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

返回 Declaration

声明#replaceWith()

在当前节点之前插入节点并移除当前节点。

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
参数类型描述
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]替换当前模式的模式。

返回 Declaration

声明#root()

查找节点树的 Root 实例。

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

返回 Root

声明#source

它表示与节点的来源相关的信息,并且是生成源映射所必需的。

使用 PostCSS 提供的公共 API 手动创建的节点将具有未定义的 source,并且在源映射中将不存在。

出于此原因,插件开发人员应考虑复制节点,因为默认情况下复制的节点将与原始节点具有相同的源,或将源分配给手动创建的节点。

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

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

 atrule.parent.insertBefore(atrule, rule)
}

类型:Source

声明#toJSON()

修复 JSON.stringify() 上的循环链接。

返回 object

声明#toString()

根据其类型将节点编译为浏览器可读的层叠样式表字符串。

new Rule({ selector: 'a' }).toString() //=> "a {}"
参数类型描述
stringifierStringifier | Syntax<Document_ | Root>在字符串生成中使用的语法。

返回 string

声明#type

它表示抽象语法树中节点的类型。

节点的类型有助于识别节点并根据其类型执行操作。

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

declaration.type //=> 'decl'

类型:“decl”。

声明#value

CSS 声明的属性值。

值字符串中的所有 CSS 注释都将被过滤掉。源值中存在的 CSS 注释将在 raws 属性中提供。

分配新的 value 会在将节点编译成字符串时忽略 raws 属性中的注释。

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

decl.value //=> 'black'

类型:字符串。

声明#variable

它表示一个 getter,如果一个声明以 --$ 开头,则返回 true,这些符号用于在 CSS 和 SASS/SCSS 中声明变量。

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

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

one.variable //=> true

类型:布尔值。

声明#warn()

它是 Result#warn 的包装器,提供了生成警告的便捷方式。

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
参数类型描述
resultResult<Document_ | Root>将接收警告的 Result 实例。
messagestring警告的描述。
optionsWarningOptions警告的选项。

返回 Warning

Document

表示一个文件并包含其所有已解析的节点。

实验性:此节点的某些方面可能会在小版本或补丁版本发布中发生变化。

const document = htmlParser(
  '<html><style>a{color:black}</style><style>b{z-index:2}</style>'
)
document.type         //=> 'document'
document.nodes.length //=> 2

文档#after()

在当前节点的父节点中将新节点插入到当前节点之后。

只是 node.parent.insertAfter(node, add) 的别名。

decl.after('color: black')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 文档

文档#append()

将新节点插入到容器的末尾。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.append(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 文档

文档#assign()

它将属性分配给现有的节点实例。

decl.assign({ prop: 'word-wrap', value: 'break-word' })
参数类型描述
overrides对象 | DocumentProps要覆盖节点的新属性。

返回 文档

文档#before()

在当前节点的父节点中将新节点插入到当前节点之前。

只是 node.parent.insertBefore(node, add) 的别名。

decl.before('content: ""')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 文档

文档#cleanRaws()

清除节点及其子节点的代码样式属性。

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
参数类型描述
keepBetweenboolean保留 raws.between 符号。

文档#clone()

它创建现有节点的克隆,其中包括所有属性及其值,包括 raws 但不包括 type

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
参数类型描述
overridesPartial<DocumentProps>在克隆中要覆盖的新属性。

返回 文档

文档#cloneAfter()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之后。

参数类型描述
overridesPartial<DocumentProps>在克隆中要覆盖的新属性。

返回 文档

文档#cloneBefore()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之前。

decl.cloneBefore({ prop: '-moz-' + decl.prop })
参数类型描述
overridesPartial<DocumentProps>要在克隆中覆盖的新属性。

返回 文档

文档#each()

遍历容器的直接子项,为每个子项调用callback

在回调中返回false将中断迭代。

此方法仅遍历容器的直接子项。如果您需要递归遍历容器的所有后代节点,请使用Container#walk

与 for {}-cycle 或 Array#forEach 不同,如果您在迭代期间改变子节点数组,此迭代器是安全的。PostCSS 将调整当前索引以匹配更改。

const root = postcss.parse('a { color: black; z-index: 1 }')
const rule = root.first

for (const decl of rule.nodes) {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Cycle will be infinite, because cloneBefore moves the current node
  // to the next index
}

rule.each(decl => {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Will be executed only for color and z-index
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

文档#error()

它创建一个类CssSyntaxError的实例,并向此方法传递的参数分配给错误实例。

错误实例将具有错误描述、节点在源中的原始位置、显示行号和列号。

如果存在任何先前的映射,它将用于获取源的原始位置。

此处的先前映射是指由先前编译生成的源映射,例如:Less、Stylus 和 Sass。

此方法返回错误实例,而不是抛出它。

if (!variables[name]) {
  throw decl.error(`Unknown variable ${name}`, { word: name })
  // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  //   color: $black
  // a
  //          ^
  //   background: white
}
参数类型描述
messagestring错误实例的描述。
optionsNodeErrorOptions错误实例的选项。

返回CssSyntaxError_

文档#every()

如果回调对容器的所有子项返回true,则返回true

const noPrefixes = rule.every(i => i.prop[0] !== '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

文档#index()

返回childContainer#nodes数组中的索引。

rule.index( rule.nodes[2] ) //=> 2
参数类型描述
child数字 | 当前容器的子项。

返回number

文档#insertAfter()

在容器中将新节点插入旧节点之后。

参数类型描述
oldNode数字 | 子项或子项的索引。
newNode字符串 | 字符串[] | 子属性 | 子属性[] | | []新节点。

返回 文档

文档#insertBefore()

在容器中将新节点插入到旧节点之前。

rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
参数类型描述
oldNode数字 | 子项或子项的索引。
newNode字符串 | 字符串[] | 子属性 | 子属性[] | | []新节点。

返回 文档

文档#next()

返回节点父级的下一个子级。如果当前节点是最后一个子级,则返回 undefined

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

返回 ChildNode

文档#节点

包含容器子级的数组。

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

类型:[].

文档#父级

它表示当前节点的父级。

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

类型:未定义。

文档#按()定位

获取节点内部某个单词或索引的位置。

参数类型描述
optsPick<WarningOptions, "index" | "word">选项。

返回 Position

文档#在内部定位()

将字符串索引转换为行/列。

参数类型描述
indexnumber节点字符串中的符号数。

返回 Position

文档#前置()

在容器开头插入新节点。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.prepend(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 文档

文档#前一个()

返回节点父级的上一个子级。如果当前节点是第一个子级,则返回 undefined

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

返回 ChildNode

文档#推入()

在节点末尾添加子级。

rule.push(new Declaration({ prop: 'color', value: 'black' }))
参数类型描述
childRoot新节点。

返回 文档

文档#按()范围

获取节点内部某个单词或起始和结束索引的范围。起始索引包含在内;结束索引不包含在内。

参数类型描述
optsPick<WarningOptions, "index" | "word" | "endIndex">选项。

返回 Range

文档#原始()

返回 raws 值。如果节点缺少代码样式属性(因为节点是手动构建或克隆的),PostCSS 将尝试通过查看树中的其他节点来自动检测代码样式属性。

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
参数类型描述
propstring代码样式属性的名称。
defaultTypestring默认值的名称,如果值与 prop 相同,则可以省略。

返回 string

文档#原始值

它表示 css 源代码中存在的不必要的空格和字符。

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

raws 对象的属性由解析器决定,默认解析器使用以下属性

PostCSS 会过滤选择器、声明值和 at 规则参数中的注释,但它会将原始内容存储在 raws 中。

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

类型:任意。

文档#移除()

它从其父级中移除节点并删除其父级属性。

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

返回 文档

文档#全部移除()

从容器中移除所有子节点并清除其父级属性。

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

返回 文档

文档#移除子级()

从容器中移除节点并清除节点及其子节点的父级属性。

rule.nodes.length  //=> 5
rule.removeChild(decl)
rule.nodes.length  //=> 4
decl.parent        //=> undefined
参数类型描述
child数字 | 子项或子项的索引。

返回 文档

文档#替换值()

参数类型
patternstring | RegExp
replacedstring | Function
参数类型描述
patternstring | RegExp替换模式。
optionsValueOptions
replacedstring | Function

返回 文档

文档#替换为()

在当前节点之前插入节点并移除当前节点。

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
参数类型描述
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]替换当前模式的模式。

返回 文档

文档#根()

查找节点树的 Root 实例。

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

返回 Root

文档#某些()

如果回调对容器的(至少)一个子节点返回 true,则返回 true

const hasPrefix = rule.some(i => i.prop[0] === '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

文档#

它表示与节点的来源相关的信息,并且是生成源映射所必需的。

使用 PostCSS 提供的公共 API 手动创建的节点将具有未定义的 source,并且在源映射中将不存在。

出于此原因,插件开发人员应考虑复制节点,因为默认情况下复制的节点将与原始节点具有相同的源,或将源分配给手动创建的节点。

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

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

 atrule.parent.insertBefore(atrule, rule)
}

类型:Source

文档#转为 JSON()

修复 JSON.stringify() 上的循环链接。

返回 object

文档#转为结果()

返回一个表示文档的 CSS 根的结果实例。

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 })
参数类型
optionsProcessOptions<Document_ | >

返回结果<Document_ | >

文档#转为字符串()

根据其类型将节点编译为浏览器可读的层叠样式表字符串。

new Rule({ selector: 'a' }).toString() //=> "a {}"
参数类型描述
stringifierStringifier | Syntax<Document_ | Root>在字符串生成中使用的语法。

返回 string

文档#类型

它表示抽象语法树中节点的类型。

节点的类型有助于识别节点并根据其类型执行操作。

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

declaration.type //=> 'decl'

类型:“文档”。

文档#遍历()

遍历容器的后代节点,为每个节点调用回调。

与 container.each() 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

如果您只需要遍历容器的直接子项,请使用 Container#each

root.walk(node => {
  // Traverses all descendant nodes.
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

文档#遍历规则()

遍历容器的后代节点,为每个 at-rule 节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配名称的 at-rule 上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

root.walkAtRules(rule => {
  if (isOld(rule.name)) rule.remove()
})

let first = false
root.walkAtRules('charset', rule => {
  if (!first) {
    first = true
  } else {
    rule.remove()
  }
})
参数类型描述
nameFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

文档#遍历注释()

参数类型
callback函数

返回void | false

文档#遍历声明()

遍历容器的后代节点,为每个声明节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配属性的声明上。

root.walkDecls(decl => {
  checkPropertySupport(decl.prop)
})

root.walkDecls('border-radius', decl => {
  decl.remove()
})

root.walkDecls(/^background/, decl => {
  decl.value = takeFirstColorFromGradient(decl.value)
})

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

参数类型描述
propFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

文档#遍历规则()

遍历容器的后代节点,为每个规则节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配选择器的规则上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

const selectors = []
root.walkRules(rule => {
  selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
参数类型描述
selectorFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

文档#警告()

它是 Result#warn 的包装器,提供了生成警告的便捷方式。

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
参数类型描述
resultResult<Document_ | Root>将接收警告的 Result 实例。
messagestring警告的描述。
optionsWarningOptions警告的选项。

返回 Warning

Input

表示源 CSS。

const root  = postcss.parse(css, { from: file })
const input = root.source.input

输入#css

输入 CSS 源。

const input = postcss.parse('a{}', { from: file }).input
input.css //=> "a{}"

类型:字符串。

输入#错误()

参数类型
messagestring
开始对象 | 对象
结束对象 | 对象
opts对象
参数类型
messagestring
linenumber
columnnumber
opts对象
参数类型
messagestring
偏移number
opts对象

返回CssSyntaxError_

输入#文件

使用from选项定义的 CSS 源文件的绝对路径。

const root = postcss.parse(css, { from: 'a.css' })
root.source.input.file //=> '/home/ai/a.css'

类型:字符串。

输入#从偏移()

将源偏移转换为行和列。

参数类型描述
偏移number源偏移。

返回对象

输入#有 BOM

指示源代码是否有 Unicode BOM 的标志。

类型:布尔值。

输入#id

CSS 源的唯一 ID。如果未提供from选项,则会创建该 ID(因为 PostCSS 不知道文件路径)。

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

类型:字符串。

输入#映射

从 PostCSS 之前的编译步骤(例如,来自 Sass 编译器)传递的输入源映射。

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

类型:PreviousMap_。

输入#来源()

读取输入源映射并返回输入源中的符号位置(例如,在传递给 PostCSS 之前编译为 CSS 的 Sass 文件中)。可以有选择地采用结束位置(不包括在内)。

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 }
参数类型描述
linenumber输入 CSS 中包含开始位置的行。
columnnumber输入 CSS 中包含开始位置的列。
endLinenumber输入 CSS 中排除结束位置的行。
endColumnnumber输入 CSS 中排除结束位置的列。

返回 false | FilePosition

LazyResult

PostCSS 转换结果的 Promise 代理。

Processor#process 返回 LazyResult 实例。

const lazy = postcss([autoprefixer]).process(css)

LazyResult#async()

以异步方式运行插件并返回 Result

返回 Promise<Result<RootNode>>

LazyResult#catch

类型:函数。

LazyResult#finally

类型:函数。

LazyResult#sync()

以同步方式运行插件并返回 Result

返回 Result<RootNode>

LazyResult#then

类型:函数。

LazyResult#toString()

LazyResult#css 属性的别名。

lazy + '' === lazy.css

返回 string

LazyResult#warnings()

通过同步插件处理输入 CSS 并调用 Result#warnings

返回 Warning[]

NoWorkResult

PostCSS 转换结果的 Promise 代理。此延迟结果实例不会解析 css,除非访问 NoWorkResult#rootResult#root。有关详细信息,请参阅以下示例。仅当未定义任何插件时,Processor#process 才返回 NoWork 实例。

const noWorkResult = postcss().process(css) // No plugins are defined.
                                            // CSS is not parsed
let root = noWorkResult.root // now css is parsed because we accessed the root

NoWorkResult#async()

以异步方式运行插件并返回 Result

返回 Promise<Result<Root>>

NoWorkResult#catch

类型:函数。

NoWorkResult#finally

类型:函数。

NoWorkResult#sync()

以同步方式运行插件并返回 Result

返回 Result<Root>

NoWorkResult#then

类型:函数。

NoWorkResult#toString()

LazyResult#css 属性的别名。

lazy + '' === lazy.css

返回 string

NoWorkResult#warnings()

通过同步插件处理输入 CSS 并调用 Result#warnings

返回 Warning[]

节点

Node#after()

在当前节点的父节点中将新节点插入到当前节点之后。

只是 node.parent.insertAfter(node, add) 的别名。

decl.after('color: black')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Node

Node#assign()

它将属性分配给现有的节点实例。

decl.assign({ prop: 'word-wrap', value: 'break-word' })
参数类型描述
overridesobject要覆盖节点的新属性。

返回 Node

Node#before()

在当前节点的父节点中将新节点插入到当前节点之前。

只是 node.parent.insertBefore(node, add) 的别名。

decl.before('content: ""')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Node

Node#cleanRaws()

清除节点及其子节点的代码样式属性。

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
参数类型描述
keepBetweenboolean保留 raws.between 符号。

Node#clone()

它创建现有节点的克隆,其中包括所有属性及其值,包括 raws 但不包括 type

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
参数类型描述
overridesobject在克隆中要覆盖的新属性。

返回 Node

Node#cloneAfter()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之后。

参数类型描述
overridesobject在克隆中要覆盖的新属性。

返回 Node

Node#cloneBefore()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之前。

decl.cloneBefore({ prop: '-moz-' + decl.prop })
参数类型描述
overridesobject要在克隆中覆盖的新属性。

返回 Node

Node#error()

它创建一个类CssSyntaxError的实例,并向此方法传递的参数分配给错误实例。

错误实例将具有错误描述、节点在源中的原始位置、显示行号和列号。

如果存在任何先前的映射,它将用于获取源的原始位置。

此处的先前映射是指由先前编译生成的源映射,例如:Less、Stylus 和 Sass。

此方法返回错误实例,而不是抛出它。

if (!variables[name]) {
  throw decl.error(`Unknown variable ${name}`, { word: name })
  // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  //   color: $black
  // a
  //          ^
  //   background: white
}
参数类型描述
messagestring错误实例的描述。
optionsNodeErrorOptions错误实例的选项。

返回CssSyntaxError_

Node#next()

返回节点父级的下一个子级。如果当前节点是最后一个子级,则返回 undefined

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

返回 ChildNode

Node#parent

它表示当前节点的父级。

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

类型:容器_<子节点> | 文档_。

Node#positionBy()

获取节点内部某个单词或索引的位置。

参数类型描述
optsPick<WarningOptions, "index" | "word">选项。

返回 Position

Node#positionInside()

将字符串索引转换为行/列。

参数类型描述
indexnumber节点字符串中的符号数。

返回 Position

Node#prev()

返回节点父级的上一个子级。如果当前节点是第一个子级,则返回 undefined

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

返回 ChildNode

Node#rangeBy()

获取节点内部某个单词或起始和结束索引的范围。起始索引包含在内;结束索引不包含在内。

参数类型描述
optsPick<WarningOptions, "index" | "word" | "endIndex">选项。

返回 Range

Node#raw()

返回 raws 值。如果节点缺少代码样式属性(因为节点是手动构建或克隆的),PostCSS 将尝试通过查看树中的其他节点来自动检测代码样式属性。

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
参数类型描述
propstring代码样式属性的名称。
defaultTypestring默认值的名称,如果值与 prop 相同,则可以省略。

返回 string

Node#raws

它表示 css 源代码中存在的不必要的空格和字符。

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

raws 对象的属性由解析器决定,默认解析器使用以下属性

PostCSS 会过滤选择器、声明值和 at 规则参数中的注释,但它会将原始内容存储在 raws 中。

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

类型:任意。

Node#remove()

它从其父级中移除节点并删除其父级属性。

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

返回 Node

Node#replaceWith()

在当前节点之前插入节点并移除当前节点。

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
参数类型描述
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]替换当前模式的模式。

返回 Node

Node#root()

查找节点树的 Root 实例。

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

返回 Root

Node#source

它表示与节点的来源相关的信息,并且是生成源映射所必需的。

使用 PostCSS 提供的公共 API 手动创建的节点将具有未定义的 source,并且在源映射中将不存在。

出于此原因,插件开发人员应考虑复制节点,因为默认情况下复制的节点将与原始节点具有相同的源,或将源分配给手动创建的节点。

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

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

 atrule.parent.insertBefore(atrule, rule)
}

类型:Source

Node#toJSON()

修复 JSON.stringify() 上的循环链接。

返回 object

Node#toString()

根据其类型将节点编译为浏览器可读的层叠样式表字符串。

new Rule({ selector: 'a' }).toString() //=> "a {}"
参数类型描述
stringifierStringifier | Syntax<Document_ | Root>在字符串生成中使用的语法。

返回 string

Node#type

它表示抽象语法树中节点的类型。

节点的类型有助于识别节点并根据其类型执行操作。

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

declaration.type //=> 'decl'

类型:字符串。

Node#warn()

它是 Result#warn 的包装器,提供了生成警告的便捷方式。

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
参数类型描述
resultResult<Document_ | Root>将接收警告的 Result 实例。
messagestring警告的描述。
optionsWarningOptions警告的选项。

返回 Warning

PreviousMap

输入 CSS 中的源映射信息。例如,Sass 编译器之后的源映射。

此类将在输入 CSS 或输入文件附近的 file 系统中自动查找源映射(根据 from 选项)。

const root = parse(css, { from: 'a.sass.css' })
root.input.map //=> PreviousMap

PreviousMap#annotation

sourceMappingURL 内容。

类型:字符串。

PreviousMap#consumer()

source-map 库创建 SourceMapGenerator 类的实例,以处理源映射信息。

这是一个惰性方法,因此它只会在第一次调用时创建对象,然后使用缓存。

返回 SourceMapConsumer

PreviousMap#file

CSS 源标识符。如果用户设置了 from 选项,则包含 Input#file;如果用户没有设置,则包含 Input#id

类型:字符串。

PreviousMap#inline

源映射是否通过 data-uri 内联到输入 CSS 中。

类型:布尔值。

PreviousMap#mapFile

源映射文件的路径。

类型:字符串。

PreviousMap#root

源映射文件的目录(如果源映射位于单独的文件中)。

类型:字符串。

PreviousMap#text

源映射文件内容。

类型:字符串。

PreviousMap#withContent()

源映射是否包含带有输入源文本的 sourcesContent

返回boolean

处理器

包含用于处理 CSS 的插件。创建一个 Processor 实例,初始化其插件,然后在多个 CSS 文件上使用该实例。

const processor = postcss([autoprefixer, postcssNested])
processor.process(css1).then(result => console.log(result.css))
processor.process(css2).then(result => console.log(result.css))

Processor#plugins

添加到此处理器的插件。

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

类型:(Plugin | TransformCallback | Transformer)[].

Processor#process()

解析源 CSS 并返回一个 LazyResult Promise 代理。由于某些插件可能是异步的,因此它不会进行任何转换。转换将在 LazyResult 方法中应用。

processor.process(css, { from: 'a.css', to: 'a.out.css' })
  .then(result => {
     console.log(result.css)
  })
参数类型描述
cssstring | Root | Result<Document_ | Root> | Object | LazyResult_<Document_ | Root>包含输入 CSS 的字符串或具有 toString() 方法的任何对象,例如 Buffer。另外,发送一个 Result 实例,处理器将从中获取 Root
参数类型描述
cssstring | Root | Result<Document_ | Root> | LazyResult_<Document_ | Root> | Object包含输入 CSS 的字符串或具有 toString() 方法的任何对象,例如 Buffer。另外,发送一个 Result 实例,处理器将从中获取 Root
optionsProcessOptions<RootNode>

返回 NoWorkResult_ | LazyResult_<Document_ | Root>

Processor#use()

添加一个插件以用作 CSS 处理器。

PostCSS 插件可以采用 4 种格式

在创建 postcss 实例时,还可以通过将插件作为参数传递来添加插件(请参阅 [postcss(plugins)])。

异步插件应返回一个 Promise 实例。

const processor = postcss()
  .use(autoprefixer)
  .use(postcssNested)
参数类型描述
pluginAcceptedPlugin带有插件的 PostCSS 插件或 Processor

返回 Processor

Processor#version

当前 PostCSS 版本。

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

类型:字符串。

Result

提供 PostCSS 转换的结果。

Result 实例由 LazyResult#thenRoot#toResult 方法返回。

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

Result#css

表示 Result#root 的 CSS 字符串。

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

类型:字符串。

Result#lastPlugin

最后运行的 PostCSS 插件。

类型:Plugin | TransformCallback

Result#map

来自 source-map 库的 SourceMapGenerator 类的实例,表示对 Result#root 实例的更改。

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

类型:SourceMap

Result#messages

包含插件消息(例如,警告或自定义消息)。每条消息都应具有类型和插件属性。

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

类型:Message[].

Result#opts

从生成此 Result 实例的Processor#processRoot#toResult调用中获取的选项。]

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

类型:ResultOptions.

Result#processor

用于此转换的 Processor 实例。

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

类型:Processor.

Result#root

所有转换后的根节点。

root.toResult().root === root

类型:RootNode。

Result#toString()

返回Result#css内容。

result + '' === result.css

返回 string

Result#warn()

创建一个Warning实例并将其添加到Result#messages中。

if (decl.important) {
  result.warn('Avoid !important', { node: decl, word: '!important' })
}
参数类型
messagestring
optionsWarningOptions

返回 Warning

Result#warnings()

返回插件警告。从Result#messages中筛选Warning实例。

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

返回 Warning[]

Root

表示 CSS 文件并包含其所有已解析的节点。

const root = postcss.parse('a{color:black} b{z-index:2}')
root.type         //=> 'root'
root.nodes.length //=> 2

Root#after()

在当前节点的父节点中将新节点插入到当前节点之后。

只是 node.parent.insertAfter(node, add) 的别名。

decl.after('color: black')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Root

Root#append()

将新节点插入到容器的末尾。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.append(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 Root

Root#assign()

它将属性分配给现有的节点实例。

decl.assign({ prop: 'word-wrap', value: 'break-word' })
参数类型描述
overridesobject | RootProps要覆盖节点的新属性。

返回 Root

Root#before()

在当前节点的父节点中将新节点插入到当前节点之前。

只是 node.parent.insertBefore(node, add) 的别名。

decl.before('content: ""')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Root

Root#cleanRaws()

清除节点及其子节点的代码样式属性。

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
参数类型描述
keepBetweenboolean保留 raws.between 符号。

Root#clone()

它创建现有节点的克隆,其中包括所有属性及其值,包括 raws 但不包括 type

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
参数类型描述
overridesPartial<RootProps>在克隆中要覆盖的新属性。

返回 Root

Root#cloneAfter()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之后。

参数类型描述
overridesPartial<RootProps>在克隆中要覆盖的新属性。

返回 Root

Root#cloneBefore()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之前。

decl.cloneBefore({ prop: '-moz-' + decl.prop })
参数类型描述
overridesPartial<RootProps>要在克隆中覆盖的新属性。

返回 Root

Root#each()

遍历容器的直接子项,为每个子项调用callback

在回调中返回false将中断迭代。

此方法仅遍历容器的直接子项。如果您需要递归遍历容器的所有后代节点,请使用Container#walk

与 for {}-cycle 或 Array#forEach 不同,如果您在迭代期间改变子节点数组,此迭代器是安全的。PostCSS 将调整当前索引以匹配更改。

const root = postcss.parse('a { color: black; z-index: 1 }')
const rule = root.first

for (const decl of rule.nodes) {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Cycle will be infinite, because cloneBefore moves the current node
  // to the next index
}

rule.each(decl => {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Will be executed only for color and z-index
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

Root#error()

它创建一个类CssSyntaxError的实例,并向此方法传递的参数分配给错误实例。

错误实例将具有错误描述、节点在源中的原始位置、显示行号和列号。

如果存在任何先前的映射,它将用于获取源的原始位置。

此处的先前映射是指由先前编译生成的源映射,例如:Less、Stylus 和 Sass。

此方法返回错误实例,而不是抛出它。

if (!variables[name]) {
  throw decl.error(`Unknown variable ${name}`, { word: name })
  // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  //   color: $black
  // a
  //          ^
  //   background: white
}
参数类型描述
messagestring错误实例的描述。
optionsNodeErrorOptions错误实例的选项。

返回CssSyntaxError_

Root#every()

如果回调对容器的所有子项返回true,则返回true

const noPrefixes = rule.every(i => i.prop[0] !== '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

Root#index()

返回childContainer#nodes数组中的索引。

rule.index( rule.nodes[2] ) //=> 2
参数类型描述
childnumber | ChildNode当前容器的子项。

返回number

Root#insertAfter()

在容器中将新节点插入旧节点之后。

参数类型描述
oldNodenumber | ChildNode子项或子项的索引。
newNodestring | string[] | ChildNode | ChildProps | ChildNode[] | ChildProps[]新节点。

返回 Root

Root#insertBefore()

在容器中将新节点插入到旧节点之前。

rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
参数类型描述
oldNodenumber | ChildNode子项或子项的索引。
newNodestring | string[] | ChildNode | ChildProps | ChildNode[] | ChildProps[]新节点。

返回 Root

Root#next()

返回节点父级的下一个子级。如果当前节点是最后一个子级,则返回 undefined

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

返回 ChildNode

Root#nodes

包含容器子级的数组。

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

类型:ChildNode[].

Root#parent

它表示当前节点的父级。

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

类型:Document_。

Root#positionBy()

获取节点内部某个单词或索引的位置。

参数类型描述
optsPick<WarningOptions, "index" | "word">选项。

返回 Position

Root#positionInside()

将字符串索引转换为行/列。

参数类型描述
indexnumber节点字符串中的符号数。

返回 Position

Root#prepend()

在容器开头插入新节点。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.prepend(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 Root

Root#prev()

返回节点父级的上一个子级。如果当前节点是第一个子级,则返回 undefined

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

返回 ChildNode

Root#push()

在节点末尾添加子级。

rule.push(new Declaration({ prop: 'color', value: 'black' }))
参数类型描述
childChildNode新节点。

返回 Root

Root#rangeBy()

获取节点内部某个单词或起始和结束索引的范围。起始索引包含在内;结束索引不包含在内。

参数类型描述
optsPick<WarningOptions, "index" | "word" | "endIndex">选项。

返回 Range

Root#raw()

返回 raws 值。如果节点缺少代码样式属性(因为节点是手动构建或克隆的),PostCSS 将尝试通过查看树中的其他节点来自动检测代码样式属性。

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
参数类型描述
propstring代码样式属性的名称。
defaultTypestring默认值的名称,如果值与 prop 相同,则可以省略。

返回 string

Root#raws

它表示 css 源代码中存在的不必要的空格和字符。

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

raws 对象的属性由解析器决定,默认解析器使用以下属性

PostCSS 会过滤选择器、声明值和 at 规则参数中的注释,但它会将原始内容存储在 raws 中。

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

类型:RootRaws.

Root#remove()

它从其父级中移除节点并删除其父级属性。

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

返回 Root

Root#removeAll()

从容器中移除所有子节点并清除其父级属性。

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

返回 Root

Root#removeChild()

从容器中移除节点并清除节点及其子节点的父级属性。

rule.nodes.length  //=> 5
rule.removeChild(decl)
rule.nodes.length  //=> 4
decl.parent        //=> undefined
参数类型描述
childnumber | ChildNode子项或子项的索引。

返回 Root

Root#replaceValues()

参数类型
patternstring | RegExp
replacedstring | Function
参数类型描述
patternstring | RegExp替换模式。
optionsValueOptions
replacedstring | Function

返回 Root

Root#replaceWith()

在当前节点之前插入节点并移除当前节点。

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
参数类型描述
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]替换当前模式的模式。

返回 Root

Root#root()

查找节点树的 Root 实例。

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

返回 Root

Root#some()

如果回调对容器的(至少)一个子节点返回 true,则返回 true

const hasPrefix = rule.some(i => i.prop[0] === '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

Root#source

它表示与节点的来源相关的信息,并且是生成源映射所必需的。

使用 PostCSS 提供的公共 API 手动创建的节点将具有未定义的 source,并且在源映射中将不存在。

出于此原因,插件开发人员应考虑复制节点,因为默认情况下复制的节点将与原始节点具有相同的源,或将源分配给手动创建的节点。

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

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

 atrule.parent.insertBefore(atrule, rule)
}

类型:Source

Root#toJSON()

修复 JSON.stringify() 上的循环链接。

返回 object

Root#toResult()

返回一个表示根 CSS 的 Result 实例。

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 })
参数类型
optionsProcessOptions<Document_ | >

返回结果<Document_ | >

Root#toString()

根据其类型将节点编译为浏览器可读的层叠样式表字符串。

new Rule({ selector: 'a' }).toString() //=> "a {}"
参数类型描述
stringifierStringifier | Syntax<Document_ | Root>在字符串生成中使用的语法。

返回 string

Root#type

它表示抽象语法树中节点的类型。

节点的类型有助于识别节点并根据其类型执行操作。

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

declaration.type //=> 'decl'

类型:“root”。

Root#walk()

遍历容器的后代节点,为每个节点调用回调。

与 container.each() 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

如果您只需要遍历容器的直接子项,请使用 Container#each

root.walk(node => {
  // Traverses all descendant nodes.
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

Root#walkAtRules()

遍历容器的后代节点,为每个 at-rule 节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配名称的 at-rule 上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

root.walkAtRules(rule => {
  if (isOld(rule.name)) rule.remove()
})

let first = false
root.walkAtRules('charset', rule => {
  if (!first) {
    first = true
  } else {
    rule.remove()
  }
})
参数类型描述
nameFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

Root#walkComments()

参数类型
callback函数

返回void | false

Root#walkDecls()

遍历容器的后代节点,为每个声明节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配属性的声明上。

root.walkDecls(decl => {
  checkPropertySupport(decl.prop)
})

root.walkDecls('border-radius', decl => {
  decl.remove()
})

root.walkDecls(/^background/, decl => {
  decl.value = takeFirstColorFromGradient(decl.value)
})

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

参数类型描述
propFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

Root#walkRules()

遍历容器的后代节点,为每个规则节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配选择器的规则上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

const selectors = []
root.walkRules(rule => {
  selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
参数类型描述
selectorFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

Root#warn()

它是 Result#warn 的包装器,提供了生成警告的便捷方式。

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
参数类型描述
resultResult<Document_ | Root>将接收警告的 Result 实例。
messagestring警告的描述。
optionsWarningOptions警告的选项。

返回 Warning

Rule

表示一个 CSS 规则:一个选择器后跟一个声明块。

Once (root, { Rule }) {
  let a = new Rule({ selector: 'a' })
  a.append(…)
  root.append(a)
}
const root = postcss.parse('a{}')
const rule = root.first
rule.type       //=> 'rule'
rule.toString() //=> 'a{}'

Rule#after()

在当前节点的父节点中将新节点插入到当前节点之后。

只是 node.parent.insertAfter(node, add) 的别名。

decl.after('color: black')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Rule

Rule#append()

将新节点插入到容器的末尾。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.append(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 Rule

Rule#assign()

它将属性分配给现有的节点实例。

decl.assign({ prop: 'word-wrap', value: 'break-word' })
参数类型描述
overridesobject | RuleProps要覆盖节点的新属性。

返回 Rule

Rule#before()

在当前节点的父节点中将新节点插入到当前节点之前。

只是 node.parent.insertBefore(node, add) 的别名。

decl.before('content: ""')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Rule

Rule#cleanRaws()

清除节点及其子节点的代码样式属性。

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
参数类型描述
keepBetweenboolean保留 raws.between 符号。

Rule#clone()

它创建现有节点的克隆,其中包括所有属性及其值,包括 raws 但不包括 type

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
参数类型描述
overridesPartial<RuleProps>在克隆中要覆盖的新属性。

返回 Rule

Rule#cloneAfter()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之后。

参数类型描述
overridesPartial<RuleProps>在克隆中要覆盖的新属性。

返回 Rule

Rule#cloneBefore()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之前。

decl.cloneBefore({ prop: '-moz-' + decl.prop })
参数类型描述
overridesPartial<RuleProps>要在克隆中覆盖的新属性。

返回 Rule

Rule#each()

遍历容器的直接子项,为每个子项调用callback

在回调中返回false将中断迭代。

此方法仅遍历容器的直接子项。如果您需要递归遍历容器的所有后代节点,请使用Container#walk

与 for {}-cycle 或 Array#forEach 不同,如果您在迭代期间改变子节点数组,此迭代器是安全的。PostCSS 将调整当前索引以匹配更改。

const root = postcss.parse('a { color: black; z-index: 1 }')
const rule = root.first

for (const decl of rule.nodes) {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Cycle will be infinite, because cloneBefore moves the current node
  // to the next index
}

rule.each(decl => {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Will be executed only for color and z-index
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

Rule#error()

它创建一个类CssSyntaxError的实例,并向此方法传递的参数分配给错误实例。

错误实例将具有错误描述、节点在源中的原始位置、显示行号和列号。

如果存在任何先前的映射,它将用于获取源的原始位置。

此处的先前映射是指由先前编译生成的源映射,例如:Less、Stylus 和 Sass。

此方法返回错误实例,而不是抛出它。

if (!variables[name]) {
  throw decl.error(`Unknown variable ${name}`, { word: name })
  // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  //   color: $black
  // a
  //          ^
  //   background: white
}
参数类型描述
messagestring错误实例的描述。
optionsNodeErrorOptions错误实例的选项。

返回CssSyntaxError_

Rule#every()

如果回调对容器的所有子项返回true,则返回true

const noPrefixes = rule.every(i => i.prop[0] !== '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

Rule#index()

返回childContainer#nodes数组中的索引。

rule.index( rule.nodes[2] ) //=> 2
参数类型描述
childnumber | ChildNode当前容器的子项。

返回number

Rule#insertAfter()

在容器中将新节点插入旧节点之后。

参数类型描述
oldNodenumber | ChildNode子项或子项的索引。
newNodestring | string[] | ChildNode | ChildProps | ChildNode[] | ChildProps[]新节点。

返回 Rule

Rule#insertBefore()

在容器中将新节点插入到旧节点之前。

rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
参数类型描述
oldNodenumber | ChildNode子项或子项的索引。
newNodestring | string[] | ChildNode | ChildProps | ChildNode[] | ChildProps[]新节点。

返回 Rule

Rule#next()

返回节点父级的下一个子级。如果当前节点是最后一个子级,则返回 undefined

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

返回 ChildNode

Rule#nodes

包含容器子级的数组。

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

类型:ChildNode[].

Rule#parent

它表示当前节点的父级。

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

类型:Container_<ChildNode>。

Rule#positionBy()

获取节点内部某个单词或索引的位置。

参数类型描述
optsPick<WarningOptions, "index" | "word">选项。

返回 Position

Rule#positionInside()

将字符串索引转换为行/列。

参数类型描述
indexnumber节点字符串中的符号数。

返回 Position

Rule#prepend()

在容器开头插入新节点。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.prepend(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 Rule

Rule#prev()

返回节点父级的上一个子级。如果当前节点是第一个子级,则返回 undefined

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

返回 ChildNode

Rule#push()

在节点末尾添加子级。

rule.push(new Declaration({ prop: 'color', value: 'black' }))
参数类型描述
childChildNode新节点。

返回 Rule

Rule#rangeBy()

获取节点内部某个单词或起始和结束索引的范围。起始索引包含在内;结束索引不包含在内。

参数类型描述
optsPick<WarningOptions, "index" | "word" | "endIndex">选项。

返回 Range

Rule#raw()

返回 raws 值。如果节点缺少代码样式属性(因为节点是手动构建或克隆的),PostCSS 将尝试通过查看树中的其他节点来自动检测代码样式属性。

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
参数类型描述
propstring代码样式属性的名称。
defaultTypestring默认值的名称,如果值与 prop 相同,则可以省略。

返回 string

Rule#raws

它表示 css 源代码中存在的不必要的空格和字符。

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

raws 对象的属性由解析器决定,默认解析器使用以下属性

PostCSS 会过滤选择器、声明值和 at 规则参数中的注释,但它会将原始内容存储在 raws 中。

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

类型:RuleRaws

Rule#remove()

它从其父级中移除节点并删除其父级属性。

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

返回 Rule

Rule#removeAll()

从容器中移除所有子节点并清除其父级属性。

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

返回 Rule

Rule#removeChild()

从容器中移除节点并清除节点及其子节点的父级属性。

rule.nodes.length  //=> 5
rule.removeChild(decl)
rule.nodes.length  //=> 4
decl.parent        //=> undefined
参数类型描述
childnumber | ChildNode子项或子项的索引。

返回 Rule

Rule#replaceValues()

参数类型
patternstring | RegExp
replacedstring | Function
参数类型描述
patternstring | RegExp替换模式。
optionsValueOptions
replacedstring | Function

返回 Rule

Rule#replaceWith()

在当前节点之前插入节点并移除当前节点。

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
参数类型描述
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]替换当前模式的模式。

返回 Rule

Rule#root()

查找节点树的 Root 实例。

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

返回 Root

Rule#selector

规则的完整选择器,表示为字符串。

const root = postcss.parse('a, b { }')
const rule = root.first
rule.selector //=> 'a, b'

类型:字符串。

Rule#selectors

包含规则的各个选择器的数组。选择器组在逗号处拆分。

const root = postcss.parse('a, b { }')
const rule = root.first

rule.selector  //=> 'a, b'
rule.selectors //=> ['a', 'b']

rule.selectors = ['a', 'strong']
rule.selector //=> 'a, strong'

类型:string[]。

Rule#some()

如果回调对容器的(至少)一个子节点返回 true,则返回 true

const hasPrefix = rule.some(i => i.prop[0] === '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

Rule#source

它表示与节点的来源相关的信息,并且是生成源映射所必需的。

使用 PostCSS 提供的公共 API 手动创建的节点将具有未定义的 source,并且在源映射中将不存在。

出于此原因,插件开发人员应考虑复制节点,因为默认情况下复制的节点将与原始节点具有相同的源,或将源分配给手动创建的节点。

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

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

 atrule.parent.insertBefore(atrule, rule)
}

类型:Source

Rule#toJSON()

修复 JSON.stringify() 上的循环链接。

返回 object

Rule#toString()

根据其类型将节点编译为浏览器可读的层叠样式表字符串。

new Rule({ selector: 'a' }).toString() //=> "a {}"
参数类型描述
stringifierStringifier | Syntax<Document_ | Root>在字符串生成中使用的语法。

返回 string

Rule#type

它表示抽象语法树中节点的类型。

节点的类型有助于识别节点并根据其类型执行操作。

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

declaration.type //=> 'decl'

类型:“rule”。

Rule#walk()

遍历容器的后代节点,为每个节点调用回调。

与 container.each() 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

如果您只需要遍历容器的直接子项,请使用 Container#each

root.walk(node => {
  // Traverses all descendant nodes.
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

规则#walkAtRules()

遍历容器的后代节点,为每个 at-rule 节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配名称的 at-rule 上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

root.walkAtRules(rule => {
  if (isOld(rule.name)) rule.remove()
})

let first = false
root.walkAtRules('charset', rule => {
  if (!first) {
    first = true
  } else {
    rule.remove()
  }
})
参数类型描述
nameFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

规则#walkComments()

参数类型
callback函数

返回void | false

规则#walkDecls()

遍历容器的后代节点,为每个声明节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配属性的声明上。

root.walkDecls(decl => {
  checkPropertySupport(decl.prop)
})

root.walkDecls('border-radius', decl => {
  decl.remove()
})

root.walkDecls(/^background/, decl => {
  decl.value = takeFirstColorFromGradient(decl.value)
})

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

参数类型描述
propFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

规则#walkRules()

遍历容器的后代节点,为每个规则节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配选择器的规则上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

const selectors = []
root.walkRules(rule => {
  selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
参数类型描述
selectorFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

规则#warn()

它是 Result#warn 的包装器,提供了生成警告的便捷方式。

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
参数类型描述
resultResult<Document_ | Root>将接收警告的 Result 实例。
messagestring警告的描述。
optionsWarningOptions警告的选项。

返回 Warning

Stringifier

字符串化#atrule()

参数类型
nodeAtRule_
分号boolean

字符串化#beforeAfter()

参数类型
nodeAnyNode
检测"after" | "before"

返回 string

字符串化#block()

参数类型
nodeAnyNode
开始string

字符串化#body()

参数类型
nodeContainer_<子节点>

字符串化#builder

类型:Builder

字符串化#comment()

参数类型
nodeComment_

字符串化#decl()

参数类型
nodeDeclaration_
分号boolean

字符串化#document()

参数类型
nodeDocument_

字符串化#raw()

参数类型
nodeAnyNode
自身string
检测string

返回 string

字符串化#rawBeforeClose()

参数类型
rootRoot

返回 string

字符串化#rawBeforeComment()

参数类型
rootRoot
nodeComment_

返回 string

字符串化#rawBeforeDecl()

参数类型
rootRoot
nodeDeclaration_

返回 string

字符串化#rawBeforeOpen()

参数类型
rootRoot

返回 string

字符串化#rawBeforeRule()

参数类型
rootRoot

返回 string

字符串化#rawColon()

参数类型
rootRoot

返回 string

字符串化#rawEmptyBody()

参数类型
rootRoot

返回 string

字符串化#rawIndent()

参数类型
rootRoot

返回 string

字符串化#rawSemicolon()

参数类型
rootRoot

返回boolean

字符串化#rawValue()

参数类型
nodeAnyNode
propstring

返回 string

字符串化#root()

参数类型
nodeRoot

字符串化#rule()

参数类型
nodeRule

字符串化#stringify()

参数类型
nodeAnyNode
分号boolean

Warning

表示插件的警告。可以使用 Node#warn 创建它。

if (decl.important) {
  decl.warn(result, 'Avoid !important', { word: '!important' })
}

警告#column

此警告源的输入文件中的包含开始位置的列。

warning.column //=> 6

类型:数字。

警告#endColumn

此警告源的输入文件中的独占结束位置的列。

warning.endColumn //=> 4

类型:数字。

警告#endLine

此警告源的输入文件中的独占结束位置的行。

warning.endLine //=> 6

类型:数字。

警告#line

此警告源的输入文件中的包含开始位置的行。

warning.line //=> 5

类型:数字。

警告#node

包含导致警告的 CSS 节点。

warning.node.toString() //=> 'color: white !important'

类型:Node

警告#plugin

创建此警告的插件的名称。当您调用 Node#warn 时,它会自动填充此属性。

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

类型:字符串。

警告#文本

警告消息。

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

类型:字符串。

警告#toString()

返回警告位置和消息。

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

返回 string

警告#类型

用于从Result#messages中过滤警告的类型。始终等于"warning"

类型:“warning”。

AtRuleProps

AtRuleProps#名称

at 规则的名称。

类型:字符串。

AtRuleProps#节点

类型:(ChildNode | ChildProps)[].

AtRuleProps#参数

at 规则名称后面的参数。

类型:字符串 | 数字。

AtRuleProps#原始

用于生成与原始输入中一样的字节对字节相等的节点字符串的信息。

类型:AtRuleRaws

AtRuleProps#

类型:Source

AtRuleRaws

AtRuleRaws#之后

从节点的最后一个子节点到节点末尾的空间符号。

类型:字符串。

AtRuleRaws#名称之后

at 规则名称与其参数之间的空格。

类型:字符串。

AtRuleRaws#之前

节点之前的空格符号。它还存储声明之前的*_符号(IE hack)。

类型:字符串。

AtRuleRaws#之间

规则的最后一个参数和{之间的符号。

类型:字符串。

AtRuleRaws#参数

带注释的规则选择器。

类型:对象。

AtRuleRaws#分号

如果最后一个子节点有(可选的)分号,则包含true

类型:布尔值。

CommentProps

CommentProps#原始

用于生成与原始输入中一样的字节对字节相等的节点字符串的信息。

类型:注释 Raws

CommentProps#

类型:Source

CommentProps#文本

注释的内容。

类型:字符串。

CommentRaws

CommentRaws#之前

节点之前的空格符号。

类型:字符串。

CommentRaws#

/*和注释文本之间的空格符号。

类型:字符串。

CommentRaws#

注释文本之间的空格符号。

类型:字符串。

ContainerProps

ContainerProps#节点

类型:(ChildNode | ChildProps)[].

ContainerProps#

类型:Source

DeclarationProps

DeclarationProps#重要

声明是否具有!important注释。

类型:布尔值。

DeclarationProps#属性

声明的名称。

类型:字符串。

DeclarationProps#原始

用于生成与原始输入中一样的字节对字节相等的节点字符串的信息。

类型:DeclarationRaws

DeclarationProps#

声明的值。

类型:字符串。

DeclarationRaws

DeclarationRaws#之前

节点之前的空格符号。它还存储声明之前的*_符号(IE hack)。

类型:字符串。

DeclarationRaws#之间

声明中属性和值之间的符号。

类型:字符串。

DeclarationRaws#重要

重要声明的内容(如果它不仅仅是!important)。

类型:字符串。

DeclarationRaws#

带注释的声明值。

类型:对象。

DocumentProps

DocumentProps#nodes

类型:[].

DocumentProps#raws

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

每个解析器保存自己的属性。

类型:Record<string, any>。

DocumentProps#source

类型:Source

FilePosition

FilePosition#column

源文件中包含开始位置的列。

类型:数字。

FilePosition#endColumn

源文件中排他结束位置的列。

类型:数字。

FilePosition#endLine

源文件中排他结束位置的行。

类型:数字。

FilePosition#file

源文件的绝对路径。

类型:字符串。

FilePosition#line

源文件中包含开始位置的行。

类型:数字。

FilePosition#source

源代码。

类型:字符串。

FilePosition#url

源文件的 URL。

类型:字符串。

Message

Message#plugin

源 PostCSS 插件名称。

类型:字符串。

Message#type

消息类型。

类型:字符串。

Message

Message#plugin

源 PostCSS 插件名称。

类型:字符串。

Message#type

消息类型。

类型:字符串。

NodeErrorOptions

NodeErrorOptions#endIndex

节点字符串中应突出显示为错误源的结束索引。

类型:数字。

NodeErrorOptions#index

节点字符串中应突出显示为错误源的索引。

类型:数字。

NodeErrorOptions#plugin

创建此错误的插件名称。PostCSS 将自动设置它。

类型:字符串。

NodeErrorOptions#word

节点字符串中的一个单词,应突出显示为错误源。

类型:字符串。

NodeProps

NodeProps#source

类型:Source

OldPlugin

参数类型
optsT
参数类型
rootRoot
resultResult<Document_ | Root>

返回 Transformer

OldPlugin#postcss

类型:Transformer

OldPlugin#postcssPlugin

类型:字符串。

OldPlugin#postcssVersion

类型:字符串。

Plugin

Plugin#AtRule

将在所有AtRule节点上调用。

将在节点或子项更改时再次调用。

类型:AtRuleProcessor | Object。

Plugin#AtRuleExit

当所有子项都将处理完毕时,将在所有AtRule节点上调用。

将在节点或子项更改时再次调用。

类型:AtRuleProcessor | Object。

Plugin#Comment

将在所有Comment节点上调用。

将在节点或子项更改时再次调用。

类型:CommentProcessor。

Plugin#CommentExit

Comment事件的侦听器之后,将在所有Comment节点上调用。

将在节点或子项更改时再次调用。

类型:CommentProcessor。

Plugin#Declaration

Declaration事件的侦听器之后,将在所有Declaration节点上调用。

将在节点或子项更改时再次调用。

类型:DeclarationProcessor | Object。

插件#DeclarationExit

将在所有Declaration节点上调用。

将在节点或子项更改时再次调用。

类型:DeclarationProcessor | Object。

插件#Document

将在Document节点上调用。

将在子项更改时再次调用。

类型:DocumentProcessor。

插件#DocumentExit

将在Document节点上调用,当所有子项都将被处理时。

将在子项更改时再次调用。

类型:DocumentProcessor。

插件#Once

将在Root节点上调用一次。

类型:RootProcessor。

插件#OnceExit

将在Root节点上调用一次,当所有子项都将被处理时。

类型:RootProcessor。

插件#Root

将在Root节点上调用。

将在子项更改时再次调用。

类型:RootProcessor。

插件#RootExit

将在Root节点上调用,当所有子项都将被处理时。

将在子项更改时再次调用。

类型:RootProcessor。

插件#Rule

将在所有Rule节点上调用。

将在节点或子项更改时再次调用。

类型:RuleProcessor。

插件#RuleExit

将在所有Rule节点上调用,当所有子项都将被处理时。

将在节点或子项更改时再次调用。

类型:RuleProcessor。

插件#postcssPlugin

类型:字符串。

插件#prepare

类型:函数。

PluginCreator

参数类型
optsPluginOptions

返回 Processor | Plugin

PluginCreator#postcss

类型:true。

位置

位置#

文件中的源行。与offset相反,它从1开始。

类型:数字。

位置#

文件中的源列。

类型:数字。

位置#偏移

文件中的源偏移。它从0开始。

类型:数字。

ProcessOptions

ProcessOptions#from

CSS源文件的路径。您应始终设置from,因为它用于源映射生成和语法错误消息。

类型:字符串。

ProcessOptions#map

源映射选项

类型:布尔值 | SourceMapOptions

ProcessOptions#parser

通过字符串生成AST的函数。

类型:Parser<RootNode> | Syntax<RootNode>。

ProcessOptions#stringifier

通过AST生成字符串的类。

类型:Stringifier | Syntax<RootNode>。

ProcessOptions#syntax

包含parse和stringify的对象。

类型:语法<RootNode>。

ProcessOptions#to

输出 CSS 文件的路径。你应该始终设置 to 以生成正确的源映射。

类型:字符串。

处理器

Processor#plugins

添加到此处理器的插件。

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

类型:(Plugin | TransformCallback | Transformer)[].

Processor#process()

解析源 CSS 并返回一个 LazyResult Promise 代理。由于某些插件可能是异步的,因此它不会进行任何转换。转换将在 LazyResult 方法中应用。

processor.process(css, { from: 'a.css', to: 'a.out.css' })
  .then(result => {
     console.log(result.css)
  })
参数类型描述
cssstring | Root | Result<Document_ | Root> | Object | LazyResult_<Document_ | Root>包含输入 CSS 的字符串或具有 toString() 方法的任何对象,例如 Buffer。另外,发送一个 Result 实例,处理器将从中获取 Root
参数类型描述
cssstring | Root | Result<Document_ | Root> | LazyResult_<Document_ | Root> | Object包含输入 CSS 的字符串或具有 toString() 方法的任何对象,例如 Buffer。另外,发送一个 Result 实例,处理器将从中获取 Root
optionsProcessOptions<RootNode>

返回 NoWorkResult_ | LazyResult_<Document_ | Root>

Processor#use()

添加一个插件以用作 CSS 处理器。

PostCSS 插件可以采用 4 种格式

在创建 postcss 实例时,还可以通过将插件作为参数传递来添加插件(请参阅 [postcss(plugins)])。

异步插件应返回一个 Promise 实例。

const processor = postcss()
  .use(autoprefixer)
  .use(postcssNested)
参数类型描述
pluginAcceptedPlugin带有插件的 PostCSS 插件或 Processor

返回 Processor

Processor#version

当前 PostCSS 版本。

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

类型:字符串。

范围

Range#end

结束位置(不包括)。

类型:位置

Range#start

开始位置(包括)。

类型:位置

RangePosition

RangePosition#column

输入中的列号。

类型:数字。

RangePosition#line

输入中的行号。

类型:数字。

Result

Result#css

表示 Result#root 的 CSS 字符串。

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

类型:字符串。

Result#lastPlugin

最后运行的 PostCSS 插件。

类型:Plugin | TransformCallback

Result#map

来自 source-map 库的 SourceMapGenerator 类的实例,表示对 Result#root 实例的更改。

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

类型:SourceMap

Result#messages

包含插件消息(例如,警告或自定义消息)。每条消息都应具有类型和插件属性。

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

类型:Message[].

Result#opts

从生成此 Result 实例的Processor#processRoot#toResult调用中获取的选项。]

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

类型:ResultOptions.

Result#processor

用于此转换的 Processor 实例。

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

类型:Processor.

Result#root

所有转换后的根节点。

root.toResult().root === root

类型:RootNode。

Result#toString()

返回Result#css内容。

result + '' === result.css

返回 string

Result#warn()

创建一个Warning实例并将其添加到Result#messages中。

if (decl.important) {
  result.warn('Avoid !important', { node: decl, word: '!important' })
}
参数类型
messagestring
optionsWarningOptions

返回 Warning

Result#warnings()

返回插件警告。从Result#messages中筛选Warning实例。

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

返回 Warning[]

ResultOptions

ResultOptions#from

CSS源文件的路径。您应始终设置from,因为它用于源映射生成和语法错误消息。

类型:字符串。

ResultOptions#map

源映射选项

类型:布尔值 | SourceMapOptions

ResultOptions#node

产生警告的 CSS 节点。

类型:Node

ResultOptions#parser

通过字符串生成AST的函数。

类型:语法<Document_ | > | 解析器<Document_ | >。

ResultOptions#plugin

创建此警告的插件的名称。Result#warn 将自动使用 插件#postcssPlugin 值填充它。

类型:字符串。

ResultOptions#stringifier

通过AST生成字符串的类。

类型:字符串化器 | 语法<Document_ | >。

ResultOptions#syntax

包含parse和stringify的对象。

类型:语法<Document_ | >。

ResultOptions#to

输出 CSS 文件的路径。你应该始终设置 to 以生成正确的源映射。

类型:字符串。

Root

Root#after()

在当前节点的父节点中将新节点插入到当前节点之后。

只是 node.parent.insertAfter(node, add) 的别名。

decl.after('color: black')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Root

Root#append()

将新节点插入到容器的末尾。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.append(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 Root

Root#assign()

它将属性分配给现有的节点实例。

decl.assign({ prop: 'word-wrap', value: 'break-word' })
参数类型描述
overridesobject | RootProps要覆盖节点的新属性。

返回 Root

Root#before()

在当前节点的父节点中将新节点插入到当前节点之前。

只是 node.parent.insertBefore(node, add) 的别名。

decl.before('content: ""')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Root

Root#cleanRaws()

清除节点及其子节点的代码样式属性。

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
参数类型描述
keepBetweenboolean保留 raws.between 符号。

Root#clone()

它创建现有节点的克隆,其中包括所有属性及其值,包括 raws 但不包括 type

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
参数类型描述
overridesPartial<RootProps>在克隆中要覆盖的新属性。

返回 Root

Root#cloneAfter()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之后。

参数类型描述
overridesPartial<RootProps>在克隆中要覆盖的新属性。

返回 Root

Root#cloneBefore()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之前。

decl.cloneBefore({ prop: '-moz-' + decl.prop })
参数类型描述
overridesPartial<RootProps>要在克隆中覆盖的新属性。

返回 Root

Root#each()

遍历容器的直接子项,为每个子项调用callback

在回调中返回false将中断迭代。

此方法仅遍历容器的直接子项。如果您需要递归遍历容器的所有后代节点,请使用Container#walk

与 for {}-cycle 或 Array#forEach 不同,如果您在迭代期间改变子节点数组,此迭代器是安全的。PostCSS 将调整当前索引以匹配更改。

const root = postcss.parse('a { color: black; z-index: 1 }')
const rule = root.first

for (const decl of rule.nodes) {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Cycle will be infinite, because cloneBefore moves the current node
  // to the next index
}

rule.each(decl => {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Will be executed only for color and z-index
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

Root#error()

它创建一个类CssSyntaxError的实例,并向此方法传递的参数分配给错误实例。

错误实例将具有错误描述、节点在源中的原始位置、显示行号和列号。

如果存在任何先前的映射,它将用于获取源的原始位置。

此处的先前映射是指由先前编译生成的源映射,例如:Less、Stylus 和 Sass。

此方法返回错误实例,而不是抛出它。

if (!variables[name]) {
  throw decl.error(`Unknown variable ${name}`, { word: name })
  // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  //   color: $black
  // a
  //          ^
  //   background: white
}
参数类型描述
messagestring错误实例的描述。
optionsNodeErrorOptions错误实例的选项。

返回CssSyntaxError_

Root#every()

如果回调对容器的所有子项返回true,则返回true

const noPrefixes = rule.every(i => i.prop[0] !== '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

Root#index()

返回childContainer#nodes数组中的索引。

rule.index( rule.nodes[2] ) //=> 2
参数类型描述
childnumber | ChildNode当前容器的子项。

返回number

Root#insertAfter()

在容器中将新节点插入旧节点之后。

参数类型描述
oldNodenumber | ChildNode子项或子项的索引。
newNodestring | string[] | ChildNode | ChildProps | ChildNode[] | ChildProps[]新节点。

返回 Root

Root#insertBefore()

在容器中将新节点插入到旧节点之前。

rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
参数类型描述
oldNodenumber | ChildNode子项或子项的索引。
newNodestring | string[] | ChildNode | ChildProps | ChildNode[] | ChildProps[]新节点。

返回 Root

Root#next()

返回节点父级的下一个子级。如果当前节点是最后一个子级,则返回 undefined

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

返回 ChildNode

Root#nodes

包含容器子级的数组。

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

类型:ChildNode[].

Root#parent

它表示当前节点的父级。

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

类型:Document_。

Root#positionBy()

获取节点内部某个单词或索引的位置。

参数类型描述
optsPick<WarningOptions, "index" | "word">选项。

返回 Position

Root#positionInside()

将字符串索引转换为行/列。

参数类型描述
indexnumber节点字符串中的符号数。

返回 Position

Root#prepend()

在容器开头插入新节点。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.prepend(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 Root

Root#prev()

返回节点父级的上一个子级。如果当前节点是第一个子级,则返回 undefined

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

返回 ChildNode

Root#push()

在节点末尾添加子级。

rule.push(new Declaration({ prop: 'color', value: 'black' }))
参数类型描述
childChildNode新节点。

返回 Root

Root#rangeBy()

获取节点内部某个单词或起始和结束索引的范围。起始索引包含在内;结束索引不包含在内。

参数类型描述
optsPick<WarningOptions, "index" | "word" | "endIndex">选项。

返回 Range

Root#raw()

返回 raws 值。如果节点缺少代码样式属性(因为节点是手动构建或克隆的),PostCSS 将尝试通过查看树中的其他节点来自动检测代码样式属性。

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
参数类型描述
propstring代码样式属性的名称。
defaultTypestring默认值的名称,如果值与 prop 相同,则可以省略。

返回 string

Root#raws

它表示 css 源代码中存在的不必要的空格和字符。

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

raws 对象的属性由解析器决定,默认解析器使用以下属性

PostCSS 会过滤选择器、声明值和 at 规则参数中的注释,但它会将原始内容存储在 raws 中。

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

类型:RootRaws.

Root#remove()

它从其父级中移除节点并删除其父级属性。

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

返回 Root

Root#removeAll()

从容器中移除所有子节点并清除其父级属性。

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

返回 Root

Root#removeChild()

从容器中移除节点并清除节点及其子节点的父级属性。

rule.nodes.length  //=> 5
rule.removeChild(decl)
rule.nodes.length  //=> 4
decl.parent        //=> undefined
参数类型描述
childnumber | ChildNode子项或子项的索引。

返回 Root

Root#replaceValues()

参数类型
patternstring | RegExp
replacedstring | Function
参数类型描述
patternstring | RegExp替换模式。
optionsValueOptions
replacedstring | Function

返回 Root

Root#replaceWith()

在当前节点之前插入节点并移除当前节点。

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
参数类型描述
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]替换当前模式的模式。

返回 Root

Root#root()

查找节点树的 Root 实例。

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

返回 Root

Root#some()

如果回调对容器的(至少)一个子节点返回 true,则返回 true

const hasPrefix = rule.some(i => i.prop[0] === '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

Root#source

它表示与节点的来源相关的信息,并且是生成源映射所必需的。

使用 PostCSS 提供的公共 API 手动创建的节点将具有未定义的 source,并且在源映射中将不存在。

出于此原因,插件开发人员应考虑复制节点,因为默认情况下复制的节点将与原始节点具有相同的源,或将源分配给手动创建的节点。

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

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

 atrule.parent.insertBefore(atrule, rule)
}

类型:Source

Root#toJSON()

修复 JSON.stringify() 上的循环链接。

返回 object

Root#toResult()

返回一个表示根 CSS 的 Result 实例。

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 })
参数类型
optionsProcessOptions<Document_ | >

返回结果<Document_ | >

Root#toString()

根据其类型将节点编译为浏览器可读的层叠样式表字符串。

new Rule({ selector: 'a' }).toString() //=> "a {}"
参数类型描述
stringifierStringifier | Syntax<Document_ | Root>在字符串生成中使用的语法。

返回 string

Root#type

它表示抽象语法树中节点的类型。

节点的类型有助于识别节点并根据其类型执行操作。

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

declaration.type //=> 'decl'

类型:“root”。

Root#walk()

遍历容器的后代节点,为每个节点调用回调。

与 container.each() 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

如果您只需要遍历容器的直接子项,请使用 Container#each

root.walk(node => {
  // Traverses all descendant nodes.
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

Root#walkAtRules()

遍历容器的后代节点,为每个 at-rule 节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配名称的 at-rule 上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

root.walkAtRules(rule => {
  if (isOld(rule.name)) rule.remove()
})

let first = false
root.walkAtRules('charset', rule => {
  if (!first) {
    first = true
  } else {
    rule.remove()
  }
})
参数类型描述
nameFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

Root#walkComments()

参数类型
callback函数

返回void | false

Root#walkDecls()

遍历容器的后代节点,为每个声明节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配属性的声明上。

root.walkDecls(decl => {
  checkPropertySupport(decl.prop)
})

root.walkDecls('border-radius', decl => {
  decl.remove()
})

root.walkDecls(/^background/, decl => {
  decl.value = takeFirstColorFromGradient(decl.value)
})

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

参数类型描述
propFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

Root#walkRules()

遍历容器的后代节点,为每个规则节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配选择器的规则上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

const selectors = []
root.walkRules(rule => {
  selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
参数类型描述
selectorFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

Root#warn()

它是 warn 的包装器,提供了生成警告的便捷方式。

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
参数类型描述
resultResult<Document_ | Root>将接收警告的 Result 实例。
messagestring警告的描述。
optionsWarningOptions警告的选项。

返回 Warning

RootProps

RootProps#nodes

类型:(ChildNode | ChildProps)[].

RootProps#raws

用于生成与原始输入中一样的字节对字节相等的节点字符串的信息。

类型:RootRaws.

RootProps#source

类型:Source

RootProps

RootProps#nodes

类型:(ChildNode | ChildProps)[].

RootProps#raws

用于生成与原始输入中一样的字节对字节相等的节点字符串的信息。

类型:RootRaws.

RootProps#source

类型:Source

RootRaws

RootRaws#after

最后一个子元素到文件末尾的空间符号。

类型:字符串。

RootRaws#codeAfter

文档 中时, 之后的非 CSS 代码。

实验性:此节点的某些方面可能会在小版本或补丁版本发布中发生变化。

类型:字符串。

RootRaws#codeBefore

文档 中时, 之前的非 CSS 代码。

实验性:此节点的某些方面可能会在小版本或补丁版本发布中发生变化。

类型:字符串。

RootRaws#semicolon

最后一个子元素是否具有(可选)分号。

类型:布尔值。

Rule

Rule#after()

在当前节点的父节点中将新节点插入到当前节点之后。

只是 node.parent.insertAfter(node, add) 的别名。

decl.after('color: black')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Rule

Rule#append()

将新节点插入到容器的末尾。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.append(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 Rule

Rule#assign()

它将属性分配给现有的节点实例。

decl.assign({ prop: 'word-wrap', value: 'break-word' })
参数类型描述
overridesobject | RuleProps要覆盖节点的新属性。

返回 Rule

Rule#before()

在当前节点的父节点中将新节点插入到当前节点之前。

只是 node.parent.insertBefore(node, add) 的别名。

decl.before('content: ""')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Rule

Rule#cleanRaws()

清除节点及其子节点的代码样式属性。

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
参数类型描述
keepBetweenboolean保留 raws.between 符号。

Rule#clone()

它创建现有节点的克隆,其中包括所有属性及其值,包括 raws 但不包括 type

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
参数类型描述
overridesPartial<RuleProps>在克隆中要覆盖的新属性。

返回 Rule

Rule#cloneAfter()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之后。

参数类型描述
overridesPartial<RuleProps>在克隆中要覆盖的新属性。

返回 Rule

Rule#cloneBefore()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之前。

decl.cloneBefore({ prop: '-moz-' + decl.prop })
参数类型描述
overridesPartial<RuleProps>要在克隆中覆盖的新属性。

返回 Rule

Rule#each()

遍历容器的直接子项,为每个子项调用callback

在回调中返回false将中断迭代。

此方法仅遍历容器的直接子项。如果您需要递归遍历容器的所有后代节点,请使用Container#walk

与 for {}-cycle 或 Array#forEach 不同,如果您在迭代期间改变子节点数组,此迭代器是安全的。PostCSS 将调整当前索引以匹配更改。

const root = postcss.parse('a { color: black; z-index: 1 }')
const rule = root.first

for (const decl of rule.nodes) {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Cycle will be infinite, because cloneBefore moves the current node
  // to the next index
}

rule.each(decl => {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Will be executed only for color and z-index
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

Rule#error()

它创建一个类CssSyntaxError的实例,并向此方法传递的参数分配给错误实例。

错误实例将具有错误描述、节点在源中的原始位置、显示行号和列号。

如果存在任何先前的映射,它将用于获取源的原始位置。

此处的先前映射是指由先前编译生成的源映射,例如:Less、Stylus 和 Sass。

此方法返回错误实例,而不是抛出它。

if (!variables[name]) {
  throw decl.error(`Unknown variable ${name}`, { word: name })
  // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  //   color: $black
  // a
  //          ^
  //   background: white
}
参数类型描述
messagestring错误实例的描述。
optionsNodeErrorOptions错误实例的选项。

返回CssSyntaxError_

Rule#every()

如果回调对容器的所有子项返回true,则返回true

const noPrefixes = rule.every(i => i.prop[0] !== '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

Rule#index()

返回childContainer#nodes数组中的索引。

rule.index( rule.nodes[2] ) //=> 2
参数类型描述
childnumber | ChildNode当前容器的子项。

返回number

Rule#insertAfter()

在容器中将新节点插入旧节点之后。

参数类型描述
oldNodenumber | ChildNode子项或子项的索引。
newNodestring | string[] | ChildNode | ChildProps | ChildNode[] | ChildProps[]新节点。

返回 Rule

Rule#insertBefore()

在容器中将新节点插入到旧节点之前。

rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
参数类型描述
oldNodenumber | ChildNode子项或子项的索引。
newNodestring | string[] | ChildNode | ChildProps | ChildNode[] | ChildProps[]新节点。

返回 Rule

Rule#next()

返回节点父级的下一个子级。如果当前节点是最后一个子级,则返回 undefined

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

返回 ChildNode

Rule#nodes

包含容器子级的数组。

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

类型:ChildNode[].

Rule#parent

它表示当前节点的父级。

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

类型:Container_<ChildNode>。

Rule#positionBy()

获取节点内部某个单词或索引的位置。

参数类型描述
optsPick<WarningOptions, "index" | "word">选项。

返回 Position

Rule#positionInside()

将字符串索引转换为行/列。

参数类型描述
indexnumber节点字符串中的符号数。

返回 Position

Rule#prepend()

在容器开头插入新节点。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.prepend(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 Rule

Rule#prev()

返回节点父级的上一个子级。如果当前节点是第一个子级,则返回 undefined

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

返回 ChildNode

Rule#push()

在节点末尾添加子级。

rule.push(new Declaration({ prop: 'color', value: 'black' }))
参数类型描述
childChildNode新节点。

返回 Rule

Rule#rangeBy()

获取节点内部某个单词或起始和结束索引的范围。起始索引包含在内;结束索引不包含在内。

参数类型描述
optsPick<WarningOptions, "index" | "word" | "endIndex">选项。

返回 Range

Rule#raw()

返回 raws 值。如果节点缺少代码样式属性(因为节点是手动构建或克隆的),PostCSS 将尝试通过查看树中的其他节点来自动检测代码样式属性。

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
参数类型描述
propstring代码样式属性的名称。
defaultTypestring默认值的名称,如果值与 prop 相同,则可以省略。

返回 string

Rule#raws

它表示 css 源代码中存在的不必要的空格和字符。

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

raws 对象的属性由解析器决定,默认解析器使用以下属性

PostCSS 会过滤选择器、声明值和 at 规则参数中的注释,但它会将原始内容存储在 raws 中。

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

类型:RuleRaws

Rule#remove()

它从其父级中移除节点并删除其父级属性。

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

返回 Rule

Rule#removeAll()

从容器中移除所有子节点并清除其父级属性。

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

返回 Rule

Rule#removeChild()

从容器中移除节点并清除节点及其子节点的父级属性。

rule.nodes.length  //=> 5
rule.removeChild(decl)
rule.nodes.length  //=> 4
decl.parent        //=> undefined
参数类型描述
childnumber | ChildNode子项或子项的索引。

返回 Rule

Rule#replaceValues()

参数类型
patternstring | RegExp
replacedstring | Function
参数类型描述
patternstring | RegExp替换模式。
optionsValueOptions
replacedstring | Function

返回 Rule

Rule#replaceWith()

在当前节点之前插入节点并移除当前节点。

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
参数类型描述
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]替换当前模式的模式。

返回 Rule

Rule#root()

查找节点树的 Root 实例。

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

返回 Root

Rule#selector

规则的完整选择器,表示为字符串。

const root = postcss.parse('a, b { }')
const rule = root.first
rule.selector //=> 'a, b'

类型:字符串。

Rule#selectors

包含规则的各个选择器的数组。选择器组在逗号处拆分。

const root = postcss.parse('a, b { }')
const rule = root.first

rule.selector  //=> 'a, b'
rule.selectors //=> ['a', 'b']

rule.selectors = ['a', 'strong']
rule.selector //=> 'a, strong'

类型:string[]。

Rule#some()

如果回调对容器的(至少)一个子节点返回 true,则返回 true

const hasPrefix = rule.some(i => i.prop[0] === '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

Rule#source

它表示与节点的来源相关的信息,并且是生成源映射所必需的。

使用 PostCSS 提供的公共 API 手动创建的节点将具有未定义的 source,并且在源映射中将不存在。

出于此原因,插件开发人员应考虑复制节点,因为默认情况下复制的节点将与原始节点具有相同的源,或将源分配给手动创建的节点。

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

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

 atrule.parent.insertBefore(atrule, rule)
}

类型:Source

Rule#toJSON()

修复 JSON.stringify() 上的循环链接。

返回 object

Rule#toString()

根据其类型将节点编译为浏览器可读的层叠样式表字符串。

new Rule({ selector: 'a' }).toString() //=> "a {}"
参数类型描述
stringifierStringifier | Syntax<Document_ | Root>在字符串生成中使用的语法。

返回 string

Rule#type

它表示抽象语法树中节点的类型。

节点的类型有助于识别节点并根据其类型执行操作。

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

declaration.type //=> 'decl'

类型:“rule”。

Rule#walk()

遍历容器的后代节点,为每个节点调用回调。

与 container.each() 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

如果您只需要遍历容器的直接子项,请使用 Container#each

root.walk(node => {
  // Traverses all descendant nodes.
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

规则#walkAtRules()

遍历容器的后代节点,为每个 at-rule 节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配名称的 at-rule 上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

root.walkAtRules(rule => {
  if (isOld(rule.name)) rule.remove()
})

let first = false
root.walkAtRules('charset', rule => {
  if (!first) {
    first = true
  } else {
    rule.remove()
  }
})
参数类型描述
nameFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

规则#walkComments()

参数类型
callback函数

返回void | false

规则#walkDecls()

遍历容器的后代节点,为每个声明节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配属性的声明上。

root.walkDecls(decl => {
  checkPropertySupport(decl.prop)
})

root.walkDecls('border-radius', decl => {
  decl.remove()
})

root.walkDecls(/^background/, decl => {
  decl.value = takeFirstColorFromGradient(decl.value)
})

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

参数类型描述
propFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

规则#walkRules()

遍历容器的后代节点,为每个规则节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配选择器的规则上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

const selectors = []
root.walkRules(rule => {
  selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
参数类型描述
selectorFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

规则#warn()

它是 warn 的包装器,提供了生成警告的便捷方式。

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
参数类型描述
resultResult<Document_ | Root>将接收警告的 Result 实例。
messagestring警告的描述。
optionsWarningOptions警告的选项。

返回 Warning

RuleProps

RuleProps#nodes

类型:(ChildNode | ChildProps)[].

RuleProps#raws

用于生成与原始输入中一样的字节对字节相等的节点字符串的信息。

类型:RuleRaws

RuleProps#selector

规则的选择器或选择器。

类型:字符串。

RuleProps#selectors

以字符串数组形式表示的规则选择器。

类型:string[]。

RuleProps#source

类型:Source

RuleProps

RuleProps#nodes

类型:(ChildNode | ChildProps)[].

RuleProps#raws

用于生成与原始输入中一样的字节对字节相等的节点字符串的信息。

类型:RuleRaws

RuleProps#selector

规则的选择器或选择器。

类型:字符串。

RuleProps#selectors

以字符串数组形式表示的规则选择器。

类型:string[]。

RuleProps#source

类型:Source

RuleRaws

RuleRaws#after

从节点的最后一个子节点到节点末尾的空间符号。

类型:字符串。

RuleRaws#before

节点之前的空格符号。它还存储声明之前的*_符号(IE hack)。

类型:字符串。

RuleRaws#between

规则中选择器和 { 之间的符号。

类型:字符串。

RuleRaws#ownSemicolon

如果规则后有分号,则包含 true

类型:字符串。

RuleRaws#selector

带注释的规则选择器。

类型:对象。

RuleRaws#semicolon

如果最后一个子节点有(可选的)分号,则包含true

类型:布尔值。

Source#end

节点源代码的包含结束位置。

类型:位置

Source#input

节点的源文件。

类型:Input_。

Source#start

节点源代码的包含开始位置。

类型:位置

SourceMapOptions

SourceMapOptions#absolute

在生成的源映射中使用绝对路径。

类型:布尔值。

SourceMapOptions#annotation

指示 PostCSS 应将注释添加到 CSS 中。默认情况下,PostCSS 始终会添加一条包含源映射路径的注释。PostCSS 不会向不包含任何注释的 CSS 文件添加注释。

默认情况下,PostCSS 假设您希望将源映射保存为 opts.to + '.map',并将在此注释中使用此路径。可以通过为注释提供字符串值来设置不同的路径。

如果您已设置 inline: true,则无法禁用注释。

类型:字符串 | 布尔值 | 函数。

SourceMapOptions#from

覆盖映射中的 from 源。

类型:字符串。

SourceMapOptions#inline

指示应将源映射作为 Base64 编码注释嵌入到输出 CSS 中。默认情况下,它是 true。但是,如果所有以前的映射都是外部的,而不是内联的,即使您没有设置此选项,PostCSS 也不会嵌入映射。

如果您有内联源映射,则 result.map 属性将为空,因为源映射将包含在 result.css 的文本中。

类型:布尔值。

SourceMapOptions#prev

来自先前处理步骤(例如 Sass)的源映射内容。

PostCSS 将尝试自动读取先前的源映射(基于源 CSS 中的注释),但您可以使用此选项手动识别它。

如果需要,您可以使用 prev: false 省略先前的映射。

类型:字符串 | 布尔值 | 对象 | 函数。

SourceMapOptions#sourcesContent

指示 PostCSS 应设置源映射的原始内容(例如,Sass 源)。默认情况下,它为 true。但是,如果所有以前的映射都不包含源内容,即使您未设置此选项,PostCSS 也会将其排除。

类型:布尔值。

语法

Syntax#parse

通过字符串生成AST的函数。

类型:Parser<RootNode>。

Syntax#stringify

通过AST生成字符串的类。

类型:Stringifier

转换器

参数类型
rootRoot
resultResult<Document_ | Root>

返回 void | Promise<void>

Transformer#postcssPlugin

类型:字符串。

Transformer#postcssVersion

类型:字符串。

ValueOptions

ValueOptions#fast

用于缩小值和加快正则表达式搜索的字符串。

类型:字符串。

ValueOptions#props

属性名称数组。

类型:string[]。

Warning

警告#column

此警告源的输入文件中的包含开始位置的列。

warning.column //=> 6

类型:数字。

警告#endColumn

此警告源的输入文件中的独占结束位置的列。

warning.endColumn //=> 4

类型:数字。

警告#endLine

此警告源的输入文件中的独占结束位置的行。

warning.endLine //=> 6

类型:数字。

警告#line

此警告源的输入文件中的包含开始位置的行。

warning.line //=> 5

类型:数字。

警告#node

包含导致警告的 CSS 节点。

warning.node.toString() //=> 'color: white !important'

类型:Node

警告#plugin

创建此警告的插件的名称。当您调用 Node#warn 时,它会自动填充此属性。

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

类型:字符串。

警告#文本

警告消息。

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

类型:字符串。

警告#toString()

返回警告位置和消息。

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

返回 string

警告#类型

用于从Result#messages中过滤警告的类型。始终等于"warning"

类型:“warning”。

WarningOptions

WarningOptions#end

导致警告的 CSS 节点字符串中的结束位置(不包括)。

类型:RangePosition

WarningOptions#endIndex

导致警告的 CSS 节点字符串中的结束索引(不包括)。

类型:数字。

WarningOptions#index

导致警告的 CSS 节点字符串中的开始索引(包括)。

类型:数字。

WarningOptions#node

导致警告的 CSS 节点。

类型:Node

WarningOptions#plugin

创建此警告的插件的名称。Result#warn 会自动填充此属性。

类型:字符串。

WarningOptions#start

导致警告的 CSS 节点字符串中的开始位置(包括)。

类型:RangePosition

WarningOptions#word

导致警告的 CSS 源中的单词。

类型:字符串。

WarningOptions

WarningOptions#end

导致警告的 CSS 节点字符串中的结束位置(不包括)。

类型:RangePosition

WarningOptions#endIndex

导致警告的 CSS 节点字符串中的结束索引(不包括)。

类型:数字。

WarningOptions#index

导致警告的 CSS 节点字符串中的开始索引(包括)。

类型:数字。

WarningOptions#node

导致警告的 CSS 节点。

类型:Node

WarningOptions#plugin

创建此警告的插件的名称。Result#warn 会自动填充此属性。

类型:字符串。

WarningOptions#start

导致警告的 CSS 节点字符串中的开始位置(包括)。

类型:RangePosition

WarningOptions#word

导致警告的 CSS 源中的单词。

类型:字符串。

at 规则

at-rule#after()

在当前节点的父节点中将新节点插入到当前节点之后。

只是 node.parent.insertAfter(node, add) 的别名。

decl.after('color: black')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 AtRule_

at-rule#append()

将新节点插入到容器的末尾。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.append(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 AtRule_

at-rule#assign()

它将属性分配给现有的节点实例。

decl.assign({ prop: 'word-wrap', value: 'break-word' })
参数类型描述
overridesobject | AtRuleProps要覆盖节点的新属性。

返回 AtRule_

at-rule#before()

在当前节点的父节点中将新节点插入到当前节点之前。

只是 node.parent.insertBefore(node, add) 的别名。

decl.before('content: ""')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 AtRule_

at-rule#cleanRaws()

清除节点及其子节点的代码样式属性。

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
参数类型描述
keepBetweenboolean保留 raws.between 符号。

at-rule#clone()

它创建现有节点的克隆,其中包括所有属性及其值,包括 raws 但不包括 type

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
参数类型描述
overridesPartial<AtRuleProps>在克隆中要覆盖的新属性。

返回 AtRule

at-rule#cloneAfter()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之后。

参数类型描述
overridesPartial<AtRuleProps>在克隆中要覆盖的新属性。

返回 AtRule

at-rule#cloneBefore()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之前。

decl.cloneBefore({ prop: '-moz-' + decl.prop })
参数类型描述
overridesPartial<AtRuleProps>要在克隆中覆盖的新属性。

返回 AtRule

at-rule#each()

遍历容器的直接子项,为每个子项调用callback

在回调中返回false将中断迭代。

此方法仅遍历容器的直接子项。如果您需要递归遍历容器的所有后代节点,请使用Container#walk

与 for {}-cycle 或 Array#forEach 不同,如果您在迭代期间改变子节点数组,此迭代器是安全的。PostCSS 将调整当前索引以匹配更改。

const root = postcss.parse('a { color: black; z-index: 1 }')
const rule = root.first

for (const decl of rule.nodes) {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Cycle will be infinite, because cloneBefore moves the current node
  // to the next index
}

rule.each(decl => {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Will be executed only for color and z-index
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

at-rule#error()

它创建一个类CssSyntaxError的实例,并向此方法传递的参数分配给错误实例。

错误实例将具有错误描述、节点在源中的原始位置、显示行号和列号。

如果存在任何先前的映射,它将用于获取源的原始位置。

此处的先前映射是指由先前编译生成的源映射,例如:Less、Stylus 和 Sass。

此方法返回错误实例,而不是抛出它。

if (!variables[name]) {
  throw decl.error(`Unknown variable ${name}`, { word: name })
  // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  //   color: $black
  // a
  //          ^
  //   background: white
}
参数类型描述
messagestring错误实例的描述。
optionsNodeErrorOptions错误实例的选项。

返回CssSyntaxError_

at-rule#every()

如果回调对容器的所有子项返回true,则返回true

const noPrefixes = rule.every(i => i.prop[0] !== '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

at-rule#index()

返回childContainer#nodes数组中的索引。

rule.index( rule.nodes[2] ) //=> 2
参数类型描述
childnumber | ChildNode当前容器的子项。

返回number

at-rule#insertAfter()

在容器中将新节点插入旧节点之后。

参数类型描述
oldNodenumber | ChildNode子项或子项的索引。
newNodestring | string[] | ChildNode | ChildProps | ChildNode[] | ChildProps[]新节点。

返回 AtRule_

at-rule#insertBefore()

在容器中将新节点插入到旧节点之前。

rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
参数类型描述
oldNodenumber | ChildNode子项或子项的索引。
newNodestring | string[] | ChildNode | ChildProps | ChildNode[] | ChildProps[]新节点。

返回 AtRule_

at-rule#name

at 规则的名称紧跟在 @ 之后。

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

类型:字符串。

at-rule#next()

返回节点父级的下一个子级。如果当前节点是最后一个子级,则返回 undefined

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

返回 ChildNode

at-rule#nodes

包含容器子级的数组。

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

类型:ChildNode[].

at-rule#params

at 规则的参数,即 at 规则名称后面但位于任何 {} 块之前的那些值。

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

类型:字符串。

at-rule#parent

它表示当前节点的父级。

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

类型:Container_<ChildNode>。

at-rule#positionBy()

获取节点内部某个单词或索引的位置。

参数类型描述
optsPick<WarningOptions, "index" | "word">选项。

返回 Position

at-rule#positionInside()

将字符串索引转换为行/列。

参数类型描述
indexnumber节点字符串中的符号数。

返回 Position

at-rule#prepend()

在容器开头插入新节点。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.prepend(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 AtRule_

at-rule#prev()

返回节点父级的上一个子级。如果当前节点是第一个子级,则返回 undefined

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

返回 ChildNode

at-rule#push()

在节点末尾添加子级。

rule.push(new Declaration({ prop: 'color', value: 'black' }))
参数类型描述
childChildNode新节点。

返回 AtRule_

at-rule#rangeBy()

获取节点内部某个单词或起始和结束索引的范围。起始索引包含在内;结束索引不包含在内。

参数类型描述
optsPick<WarningOptions, "index" | "word" | "endIndex">选项。

返回 Range

at-rule#raw()

返回 raws 值。如果节点缺少代码样式属性(因为节点是手动构建或克隆的),PostCSS 将尝试通过查看树中的其他节点来自动检测代码样式属性。

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
参数类型描述
propstring代码样式属性的名称。
defaultTypestring默认值的名称,如果值与 prop 相同,则可以省略。

返回 string

at-rule#raws

它表示 css 源代码中存在的不必要的空格和字符。

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

raws 对象的属性由解析器决定,默认解析器使用以下属性

PostCSS 会过滤选择器、声明值和 at 规则参数中的注释,但它会将原始内容存储在 raws 中。

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

类型:AtRuleRaws

at-rule#remove()

它从其父级中移除节点并删除其父级属性。

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

返回 AtRule_

at-rule#removeAll()

从容器中移除所有子节点并清除其父级属性。

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

返回 AtRule_

at-rule#removeChild()

从容器中移除节点并清除节点及其子节点的父级属性。

rule.nodes.length  //=> 5
rule.removeChild(decl)
rule.nodes.length  //=> 4
decl.parent        //=> undefined
参数类型描述
childnumber | ChildNode子项或子项的索引。

返回 AtRule_

at-rule#replaceValues()

参数类型
patternstring | RegExp
replacedstring | Function
参数类型描述
patternstring | RegExp替换模式。
optionsValueOptions
replacedstring | Function

返回 AtRule_

at-rule#replaceWith()

在当前节点之前插入节点并移除当前节点。

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
参数类型描述
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]替换当前模式的模式。

返回 AtRule_

at-rule#root()

查找节点树的 Root 实例。

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

返回 Root

at-rule#some()

如果回调对容器的(至少)一个子节点返回 true,则返回 true

const hasPrefix = rule.some(i => i.prop[0] === '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

at-rule#source

它表示与节点的来源相关的信息,并且是生成源映射所必需的。

使用 PostCSS 提供的公共 API 手动创建的节点将具有未定义的 source,并且在源映射中将不存在。

出于此原因,插件开发人员应考虑复制节点,因为默认情况下复制的节点将与原始节点具有相同的源,或将源分配给手动创建的节点。

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

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

 atrule.parent.insertBefore(atrule, rule)
}

类型:Source

at-rule#toJSON()

修复 JSON.stringify() 上的循环链接。

返回 object

at-rule#toString()

根据其类型将节点编译为浏览器可读的层叠样式表字符串。

new Rule({ selector: 'a' }).toString() //=> "a {}"
参数类型描述
stringifierStringifier | Syntax<Document_ | Root>在字符串生成中使用的语法。

返回 string

at-rule#type

它表示抽象语法树中节点的类型。

节点的类型有助于识别节点并根据其类型执行操作。

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

declaration.type //=> 'decl'

类型:“atrule”。

at-rule#walk()

遍历容器的后代节点,为每个节点调用回调。

与 container.each() 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

如果您只需要遍历容器的直接子项,请使用 Container#each

root.walk(node => {
  // Traverses all descendant nodes.
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

at-rule#walkAtRules()

遍历容器的后代节点,为每个 at-rule 节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配名称的 at-rule 上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

root.walkAtRules(rule => {
  if (isOld(rule.name)) rule.remove()
})

let first = false
root.walkAtRules('charset', rule => {
  if (!first) {
    first = true
  } else {
    rule.remove()
  }
})
参数类型描述
nameFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

at-rule#walkComments()

参数类型
callback函数

返回void | false

at-rule#walkDecls()

遍历容器的后代节点,为每个声明节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配属性的声明上。

root.walkDecls(decl => {
  checkPropertySupport(decl.prop)
})

root.walkDecls('border-radius', decl => {
  decl.remove()
})

root.walkDecls(/^background/, decl => {
  decl.value = takeFirstColorFromGradient(decl.value)
})

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

参数类型描述
propFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

at-rule#walkRules()

遍历容器的后代节点,为每个规则节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配选择器的规则上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

const selectors = []
root.walkRules(rule => {
  selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
参数类型描述
selectorFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

at-rule#warn()

它是 Result#warn 的包装器,提供了生成警告的便捷方式。

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
参数类型描述
resultResult<Document_ | Root>将接收警告的 Result 实例。
messagestring警告的描述。
optionsWarningOptions警告的选项。

返回 Warning

comment

comment#after()

在当前节点的父节点中将新节点插入到当前节点之后。

只是 node.parent.insertAfter(node, add) 的别名。

decl.after('color: black')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Comment_

comment#assign()

它将属性分配给现有的节点实例。

decl.assign({ prop: 'word-wrap', value: 'break-word' })
参数类型描述
overrides对象 | 注释属性要覆盖节点的新属性。

返回 Comment_

comment#before()

在当前节点的父节点中将新节点插入到当前节点之前。

只是 node.parent.insertBefore(node, add) 的别名。

decl.before('content: ""')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Comment_

comment#cleanRaws()

清除节点及其子节点的代码样式属性。

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
参数类型描述
keepBetweenboolean保留 raws.between 符号。

comment#clone()

它创建现有节点的克隆,其中包括所有属性及其值,包括 raws 但不包括 type

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
参数类型描述
overrides部分<注释属性>在克隆中要覆盖的新属性。

返回注释

comment#cloneAfter()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之后。

参数类型描述
overrides部分<注释属性>在克隆中要覆盖的新属性。

返回注释

comment#cloneBefore()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之前。

decl.cloneBefore({ prop: '-moz-' + decl.prop })
参数类型描述
overrides部分<注释属性>要在克隆中覆盖的新属性。

返回注释

comment#error()

它创建一个类CssSyntaxError的实例,并向此方法传递的参数分配给错误实例。

错误实例将具有错误描述、节点在源中的原始位置、显示行号和列号。

如果存在任何先前的映射,它将用于获取源的原始位置。

此处的先前映射是指由先前编译生成的源映射,例如:Less、Stylus 和 Sass。

此方法返回错误实例,而不是抛出它。

if (!variables[name]) {
  throw decl.error(`Unknown variable ${name}`, { word: name })
  // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  //   color: $black
  // a
  //          ^
  //   background: white
}
参数类型描述
messagestring错误实例的描述。
optionsNodeErrorOptions错误实例的选项。

返回CssSyntaxError_

comment#next()

返回节点父级的下一个子级。如果当前节点是最后一个子级,则返回 undefined

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

返回 ChildNode

comment#parent

它表示当前节点的父级。

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

类型:Container_<ChildNode>。

comment#positionBy()

获取节点内部某个单词或索引的位置。

参数类型描述
optsPick<WarningOptions, "index" | "word">选项。

返回 Position

comment#positionInside()

将字符串索引转换为行/列。

参数类型描述
indexnumber节点字符串中的符号数。

返回 Position

comment#prev()

返回节点父级的上一个子级。如果当前节点是第一个子级,则返回 undefined

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

返回 ChildNode

comment#rangeBy()

获取节点内部某个单词或起始和结束索引的范围。起始索引包含在内;结束索引不包含在内。

参数类型描述
optsPick<WarningOptions, "index" | "word" | "endIndex">选项。

返回 Range

comment#raw()

返回 raws 值。如果节点缺少代码样式属性(因为节点是手动构建或克隆的),PostCSS 将尝试通过查看树中的其他节点来自动检测代码样式属性。

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
参数类型描述
propstring代码样式属性的名称。
defaultTypestring默认值的名称,如果值与 prop 相同,则可以省略。

返回 string

comment#raws

它表示 css 源代码中存在的不必要的空格和字符。

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

raws 对象的属性由解析器决定,默认解析器使用以下属性

PostCSS 会过滤选择器、声明值和 at 规则参数中的注释,但它会将原始内容存储在 raws 中。

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

类型:注释 Raws

comment#remove()

它从其父级中移除节点并删除其父级属性。

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

返回 Comment_

comment#replaceWith()

在当前节点之前插入节点并移除当前节点。

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
参数类型描述
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]替换当前模式的模式。

返回 Comment_

comment#root()

查找节点树的 Root 实例。

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

返回 Root

comment#source

它表示与节点的来源相关的信息,并且是生成源映射所必需的。

使用 PostCSS 提供的公共 API 手动创建的节点将具有未定义的 source,并且在源映射中将不存在。

出于此原因,插件开发人员应考虑复制节点,因为默认情况下复制的节点将与原始节点具有相同的源,或将源分配给手动创建的节点。

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

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

 atrule.parent.insertBefore(atrule, rule)
}

类型:Source

comment#text

注释的文本。

类型:字符串。

comment#toJSON()

修复 JSON.stringify() 上的循环链接。

返回 object

comment#toString()

根据其类型将节点编译为浏览器可读的层叠样式表字符串。

new Rule({ selector: 'a' }).toString() //=> "a {}"
参数类型描述
stringifierStringifier | Syntax<Document_ | Root>在字符串生成中使用的语法。

返回 string

comment#type

它表示抽象语法树中节点的类型。

节点的类型有助于识别节点并根据其类型执行操作。

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

declaration.type //=> 'decl'

类型:“注释”。

comment#warn()

它是 Result#warn 的包装器,提供了生成警告的便捷方式。

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
参数类型描述
resultResult<Document_ | Root>将接收警告的 Result 实例。
messagestring警告的描述。
optionsWarningOptions警告的选项。

返回 Warning

container

container#after()

在当前节点的父节点中将新节点插入到当前节点之后。

只是 node.parent.insertAfter(node, add) 的别名。

decl.after('color: black')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Container_<Child>

container#append()

将新节点插入到容器的末尾。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.append(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 Container_<Child>

container#assign()

它将属性分配给现有的节点实例。

decl.assign({ prop: 'word-wrap', value: 'break-word' })
参数类型描述
overrides对象 | 容器属性要覆盖节点的新属性。

返回 Container_<Child>

container#before()

在当前节点的父节点中将新节点插入到当前节点之前。

只是 node.parent.insertBefore(node, add) 的别名。

decl.before('content: ""')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Container_<Child>

container#cleanRaws()

清除节点及其子节点的代码样式属性。

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
参数类型描述
keepBetweenboolean保留 raws.between 符号。

container#clone()

它创建现有节点的克隆,其中包括所有属性及其值,包括 raws 但不包括 type

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
参数类型描述
overrides部分<容器属性>在克隆中要覆盖的新属性。

返回容器<子级>

container#cloneAfter()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之后。

参数类型描述
overrides部分<容器属性>在克隆中要覆盖的新属性。

返回容器<子级>

container#cloneBefore()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之前。

decl.cloneBefore({ prop: '-moz-' + decl.prop })
参数类型描述
overrides部分<容器属性>要在克隆中覆盖的新属性。

返回容器<子级>

container#each()

遍历容器的直接子项,为每个子项调用callback

在回调中返回false将中断迭代。

此方法仅遍历容器的直接子项。如果您需要递归遍历容器的所有后代节点,请使用Container#walk

与 for {}-cycle 或 Array#forEach 不同,如果您在迭代期间改变子节点数组,此迭代器是安全的。PostCSS 将调整当前索引以匹配更改。

const root = postcss.parse('a { color: black; z-index: 1 }')
const rule = root.first

for (const decl of rule.nodes) {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Cycle will be infinite, because cloneBefore moves the current node
  // to the next index
}

rule.each(decl => {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Will be executed only for color and z-index
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

container#error()

它创建一个类CssSyntaxError的实例,并向此方法传递的参数分配给错误实例。

错误实例将具有错误描述、节点在源中的原始位置、显示行号和列号。

如果存在任何先前的映射,它将用于获取源的原始位置。

此处的先前映射是指由先前编译生成的源映射,例如:Less、Stylus 和 Sass。

此方法返回错误实例,而不是抛出它。

if (!variables[name]) {
  throw decl.error(`Unknown variable ${name}`, { word: name })
  // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  //   color: $black
  // a
  //          ^
  //   background: white
}
参数类型描述
messagestring错误实例的描述。
optionsNodeErrorOptions错误实例的选项。

返回CssSyntaxError_

container#every()

如果回调对容器的所有子项返回true,则返回true

const noPrefixes = rule.every(i => i.prop[0] !== '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

container#index()

返回childContainer#nodes数组中的索引。

rule.index( rule.nodes[2] ) //=> 2
参数类型描述
child数字 | 子级当前容器的子项。

返回number

container#insertAfter()

在容器中将新节点插入旧节点之后。

参数类型描述
oldNode数字 | 子级子项或子项的索引。
newNode字符串 | 字符串[] | 子级 | 子级属性 | 子级属性[] | 子级[]新节点。

返回 Container_<Child>

container#insertBefore()

在容器中将新节点插入到旧节点之前。

rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
参数类型描述
oldNode数字 | 子级子项或子项的索引。
newNode字符串 | 字符串[] | 子级 | 子级属性 | 子级属性[] | 子级[]新节点。

返回 Container_<Child>

container#next()

返回节点父级的下一个子级。如果当前节点是最后一个子级,则返回 undefined

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

返回 ChildNode

container#nodes

包含容器子级的数组。

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

类型:子级[]。

container#parent

它表示当前节点的父级。

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

类型:容器_<子节点> | 文档_。

container#positionBy()

获取节点内部某个单词或索引的位置。

参数类型描述
optsPick<WarningOptions, "index" | "word">选项。

返回 Position

container#positionInside()

将字符串索引转换为行/列。

参数类型描述
indexnumber节点字符串中的符号数。

返回 Position

container#prepend()

在容器开头插入新节点。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.prepend(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 Container_<Child>

container#prev()

返回节点父级的上一个子级。如果当前节点是第一个子级,则返回 undefined

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

返回 ChildNode

container#push()

在节点末尾添加子级。

rule.push(new Declaration({ prop: 'color', value: 'black' }))
参数类型描述
child子项新节点。

返回 Container_<Child>

container#rangeBy()

获取节点内部某个单词或起始和结束索引的范围。起始索引包含在内;结束索引不包含在内。

参数类型描述
optsPick<WarningOptions, "index" | "word" | "endIndex">选项。

返回 Range

container#raw()

返回 raws 值。如果节点缺少代码样式属性(因为节点是手动构建或克隆的),PostCSS 将尝试通过查看树中的其他节点来自动检测代码样式属性。

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
参数类型描述
propstring代码样式属性的名称。
defaultTypestring默认值的名称,如果值与 prop 相同,则可以省略。

返回 string

container#raws

它表示 css 源代码中存在的不必要的空格和字符。

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

raws 对象的属性由解析器决定,默认解析器使用以下属性

PostCSS 会过滤选择器、声明值和 at 规则参数中的注释,但它会将原始内容存储在 raws 中。

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

类型:任意。

container#remove()

它从其父级中移除节点并删除其父级属性。

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

返回 Container_<Child>

container#removeAll()

从容器中移除所有子节点并清除其父级属性。

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

返回 Container_<Child>

container#removeChild()

从容器中移除节点并清除节点及其子节点的父级属性。

rule.nodes.length  //=> 5
rule.removeChild(decl)
rule.nodes.length  //=> 4
decl.parent        //=> undefined
参数类型描述
child数字 | 子级子项或子项的索引。

返回 Container_<Child>

container#replaceValues()

参数类型
patternstring | RegExp
replacedstring | Function
参数类型描述
patternstring | RegExp替换模式。
optionsValueOptions
replacedstring | Function

返回 Container_<Child>

container#replaceWith()

在当前节点之前插入节点并移除当前节点。

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
参数类型描述
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]替换当前模式的模式。

返回 Container_<Child>

container#root()

查找节点树的 Root 实例。

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

返回 Root

container#some()

如果回调对容器的(至少)一个子节点返回 true,则返回 true

const hasPrefix = rule.some(i => i.prop[0] === '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

container#source

它表示与节点的来源相关的信息,并且是生成源映射所必需的。

使用 PostCSS 提供的公共 API 手动创建的节点将具有未定义的 source,并且在源映射中将不存在。

出于此原因,插件开发人员应考虑复制节点,因为默认情况下复制的节点将与原始节点具有相同的源,或将源分配给手动创建的节点。

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

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

 atrule.parent.insertBefore(atrule, rule)
}

类型:Source

container#toJSON()

修复 JSON.stringify() 上的循环链接。

返回 object

container#toString()

根据其类型将节点编译为浏览器可读的层叠样式表字符串。

new Rule({ selector: 'a' }).toString() //=> "a {}"
参数类型描述
stringifierStringifier | Syntax<Document_ | Root>在字符串生成中使用的语法。

返回 string

container#type

它表示抽象语法树中节点的类型。

节点的类型有助于识别节点并根据其类型执行操作。

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

declaration.type //=> 'decl'

类型:字符串。

container#walk()

遍历容器的后代节点,为每个节点调用回调。

与 container.each() 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

如果您只需要遍历容器的直接子项,请使用 Container#each

root.walk(node => {
  // Traverses all descendant nodes.
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

container#walkAtRules()

遍历容器的后代节点,为每个 at-rule 节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配名称的 at-rule 上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

root.walkAtRules(rule => {
  if (isOld(rule.name)) rule.remove()
})

let first = false
root.walkAtRules('charset', rule => {
  if (!first) {
    first = true
  } else {
    rule.remove()
  }
})
参数类型描述
nameFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

container#walkComments()

参数类型
callback函数

返回void | false

container#walkDecls()

遍历容器的后代节点,为每个声明节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配属性的声明上。

root.walkDecls(decl => {
  checkPropertySupport(decl.prop)
})

root.walkDecls('border-radius', decl => {
  decl.remove()
})

root.walkDecls(/^background/, decl => {
  decl.value = takeFirstColorFromGradient(decl.value)
})

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

参数类型描述
propFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

container#walkRules()

遍历容器的后代节点,为每个规则节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配选择器的规则上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

const selectors = []
root.walkRules(rule => {
  selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
参数类型描述
selectorFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

container#warn()

它是 Result#warn 的包装器,提供了生成警告的便捷方式。

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
参数类型描述
resultResult<Document_ | Root>将接收警告的 Result 实例。
messagestring警告的描述。
optionsWarningOptions警告的选项。

返回 Warning

css-syntax-error

css-syntax-error#column

错误的源列。

error.column       //=> 1
error.input.column //=> 4

PostCSS 会使用输入源映射来检测原始位置。如果您需要 PostCSS 输入中的位置,请使用 error.input.column

类型:数字。

css-syntax-error#endColumn

错误结束的源列(不包括)。如果错误涉及范围,则提供。

error.endColumn       //=> 1
error.input.endColumn //=> 4

PostCSS 会使用输入源映射来检测原始位置。如果您需要 PostCSS 输入中的位置,请使用 error.input.endColumn

类型:数字。

css-syntax-error#endLine

错误结束的源行(不包括)。如果错误涉及范围,则提供。

error.endLine       //=> 3
error.input.endLine //=> 4

PostCSS 会使用输入源映射来检测原始位置。如果您需要 PostCSS 输入中的位置,请使用 error.input.endLine

类型:数字。

css-syntax-error#file

损坏文件的绝对路径。

error.file       //=> 'a.sass'
error.input.file //=> 'a.css'

PostCSS 将使用输入源映射来检测原始位置。如果您需要 PostCSS 输入中的位置,请使用 error.input.file

类型:字符串。

css-syntax-error#input

包含有关输入文件的 PostCSS 内部信息的输入对象。如果输入具有来自先前工具的源映射,PostCSS 将使用原始(例如,Sass)源。您可以使用此对象来获取 PostCSS 输入源。

error.input.file //=> 'a.css'
error.file       //=> 'a.sass'

类型:FilePosition

css-syntax-error#line

错误的源行。

error.line       //=> 2
error.input.line //=> 4

PostCSS 将使用输入源映射来检测原始位置。如果您需要 PostCSS 输入中的位置,请使用 error.input.line

类型:数字。

css-syntax-error#message

使用插件、文件、行和列的 GNU 错误格式的完整错误文本。

error.message //=> 'a.css:1:1: Unclosed block'

类型:字符串。

css-syntax-error#name

始终等于 'CssSyntaxError'。您应始终通过 error.name === 'CssSyntaxError' 检查错误类型,而不是 error instanceof CssSyntaxError,因为 npm 可能有几个 PostCSS 版本。

if (error.name === 'CssSyntaxError') {
  error //=> CssSyntaxError
}

类型:"CssSyntaxError"。

css-syntax-error#plugin

如果错误来自插件,则为插件名称。

error.plugin //=> 'postcss-vars'

类型:字符串。

css-syntax-error#reason

错误消息。

error.message //=> 'Unclosed block'

类型:字符串。

css-syntax-error#showSourceCode()

返回导致错误的几行 CSS 源。

如果 CSS 具有没有 sourceContent 的输入源映射,此方法将返回一个空字符串。

error.showSourceCode() //=> "  4 | }
                       //      5 | a {
                       //    > 6 |   bad
                       //        |   ^
                       //      7 | }
                       //      8 | b {"
参数类型描述
colorboolean箭头是否将由终端颜色代码着色为红色。默认情况下,PostCSS 将通过 process.stdout.isTTYprocess.env.NODE_DISABLE_COLORS 检测颜色支持。

返回 string

css-syntax-error#source

损坏文件的源代码。

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

类型:字符串。

css-syntax-error#stack

类型:字符串。

css-syntax-error#toString()

返回损坏部分的错误位置、消息和源代码。

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

返回 string

声明

declaration#after()

在当前节点的父节点中将新节点插入到当前节点之后。

只是 node.parent.insertAfter(node, add) 的别名。

decl.after('color: black')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Declaration_

声明#assign()

它将属性分配给现有的节点实例。

decl.assign({ prop: 'word-wrap', value: 'break-word' })
参数类型描述
overridesobject | DeclarationProps要覆盖节点的新属性。

返回 Declaration_

声明#before()

在当前节点的父节点中将新节点插入到当前节点之前。

只是 node.parent.insertBefore(node, add) 的别名。

decl.before('content: ""')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Declaration_

声明#cleanRaws()

清除节点及其子节点的代码样式属性。

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
参数类型描述
keepBetweenboolean保留 raws.between 符号。

声明#clone()

它创建现有节点的克隆,其中包括所有属性及其值,包括 raws 但不包括 type

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
参数类型描述
overridesPartial<DeclarationProps>在克隆中要覆盖的新属性。

返回 Declaration

声明#cloneAfter()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之后。

参数类型描述
overridesPartial<DeclarationProps>在克隆中要覆盖的新属性。

返回 Declaration

声明#cloneBefore()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之前。

decl.cloneBefore({ prop: '-moz-' + decl.prop })
参数类型描述
overridesPartial<DeclarationProps>要在克隆中覆盖的新属性。

返回 Declaration

声明#error()

它创建一个类CssSyntaxError的实例,并向此方法传递的参数分配给错误实例。

错误实例将具有错误描述、节点在源中的原始位置、显示行号和列号。

如果存在任何先前的映射,它将用于获取源的原始位置。

此处的先前映射是指由先前编译生成的源映射,例如:Less、Stylus 和 Sass。

此方法返回错误实例,而不是抛出它。

if (!variables[name]) {
  throw decl.error(`Unknown variable ${name}`, { word: name })
  // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  //   color: $black
  // a
  //          ^
  //   background: white
}
参数类型描述
messagestring错误实例的描述。
optionsNodeErrorOptions错误实例的选项。

返回CssSyntaxError_

声明#important

它表示声明的特异性。

如果为真,CSS 声明将具有important说明符。

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

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

类型:布尔值。

声明#next()

返回节点父级的下一个子级。如果当前节点是最后一个子级,则返回 undefined

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

返回 ChildNode

声明#parent

它表示当前节点的父级。

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

类型:Container_<ChildNode>。

声明#positionBy()

获取节点内部某个单词或索引的位置。

参数类型描述
optsPick<WarningOptions, "index" | "word">选项。

返回 Position

声明#positionInside()

将字符串索引转换为行/列。

参数类型描述
indexnumber节点字符串中的符号数。

返回 Position

声明#prev()

返回节点父级的上一个子级。如果当前节点是第一个子级,则返回 undefined

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

返回 ChildNode

声明#prop

CSS 声明的属性名称。

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

decl.prop //=> 'color'

类型:字符串。

声明#rangeBy()

获取节点内部某个单词或起始和结束索引的范围。起始索引包含在内;结束索引不包含在内。

参数类型描述
optsPick<WarningOptions, "index" | "word" | "endIndex">选项。

返回 Range

声明#raw()

返回 raws 值。如果节点缺少代码样式属性(因为节点是手动构建或克隆的),PostCSS 将尝试通过查看树中的其他节点来自动检测代码样式属性。

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
参数类型描述
propstring代码样式属性的名称。
defaultTypestring默认值的名称,如果值与 prop 相同,则可以省略。

返回 string

声明#raws

它表示 css 源代码中存在的不必要的空格和字符。

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

raws 对象的属性由解析器决定,默认解析器使用以下属性

PostCSS 会过滤选择器、声明值和 at 规则参数中的注释,但它会将原始内容存储在 raws 中。

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

类型:DeclarationRaws

声明#remove()

它从其父级中移除节点并删除其父级属性。

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

返回 Declaration_

声明#replaceWith()

在当前节点之前插入节点并移除当前节点。

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
参数类型描述
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]替换当前模式的模式。

返回 Declaration_

声明#root()

查找节点树的 Root 实例。

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

返回 Root

声明#source

它表示与节点的来源相关的信息,并且是生成源映射所必需的。

使用 PostCSS 提供的公共 API 手动创建的节点将具有未定义的 source,并且在源映射中将不存在。

出于此原因,插件开发人员应考虑复制节点,因为默认情况下复制的节点将与原始节点具有相同的源,或将源分配给手动创建的节点。

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

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

 atrule.parent.insertBefore(atrule, rule)
}

类型:Source

声明#toJSON()

修复 JSON.stringify() 上的循环链接。

返回 object

声明#toString()

根据其类型将节点编译为浏览器可读的层叠样式表字符串。

new Rule({ selector: 'a' }).toString() //=> "a {}"
参数类型描述
stringifierStringifier | Syntax<Document_ | Root>在字符串生成中使用的语法。

返回 string

声明#type

它表示抽象语法树中节点的类型。

节点的类型有助于识别节点并根据其类型执行操作。

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

declaration.type //=> 'decl'

类型:“decl”。

声明#value

CSS 声明的属性值。

值字符串中的所有 CSS 注释都将被过滤掉。源值中存在的 CSS 注释将在 raws 属性中提供。

分配新的 value 会在将节点编译成字符串时忽略 raws 属性中的注释。

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

decl.value //=> 'black'

类型:字符串。

声明#variable

它表示一个 getter,如果一个声明以 --$ 开头,则返回 true,这些符号用于在 CSS 和 SASS/SCSS 中声明变量。

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

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

one.variable //=> true

类型:布尔值。

声明#warn()

它是 Result#warn 的包装器,提供了生成警告的便捷方式。

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
参数类型描述
resultResult<Document_ | Root>将接收警告的 Result 实例。
messagestring警告的描述。
optionsWarningOptions警告的选项。

返回 Warning

文档

文档#after()

在当前节点的父节点中将新节点插入到当前节点之后。

只是 node.parent.insertAfter(node, add) 的别名。

decl.after('color: black')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Document_

文档#append()

将新节点插入到容器的末尾。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.append(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 Document_

文档#assign()

它将属性分配给现有的节点实例。

decl.assign({ prop: 'word-wrap', value: 'break-word' })
参数类型描述
overrides对象 | DocumentProps要覆盖节点的新属性。

返回 Document_

文档#before()

在当前节点的父节点中将新节点插入到当前节点之前。

只是 node.parent.insertBefore(node, add) 的别名。

decl.before('content: ""')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Document_

文档#cleanRaws()

清除节点及其子节点的代码样式属性。

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
参数类型描述
keepBetweenboolean保留 raws.between 符号。

文档#clone()

它创建现有节点的克隆,其中包括所有属性及其值,包括 raws 但不包括 type

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
参数类型描述
overridesPartial<DocumentProps>在克隆中要覆盖的新属性。

返回 文档

文档#cloneAfter()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之后。

参数类型描述
overridesPartial<DocumentProps>在克隆中要覆盖的新属性。

返回 文档

文档#cloneBefore()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之前。

decl.cloneBefore({ prop: '-moz-' + decl.prop })
参数类型描述
overridesPartial<DocumentProps>要在克隆中覆盖的新属性。

返回 文档

文档#each()

遍历容器的直接子项,为每个子项调用callback

在回调中返回false将中断迭代。

此方法仅遍历容器的直接子项。如果您需要递归遍历容器的所有后代节点,请使用Container#walk

与 for {}-cycle 或 Array#forEach 不同,如果您在迭代期间改变子节点数组,此迭代器是安全的。PostCSS 将调整当前索引以匹配更改。

const root = postcss.parse('a { color: black; z-index: 1 }')
const rule = root.first

for (const decl of rule.nodes) {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Cycle will be infinite, because cloneBefore moves the current node
  // to the next index
}

rule.each(decl => {
  decl.cloneBefore({ prop: '-webkit-' + decl.prop })
  // Will be executed only for color and z-index
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

文档#error()

它创建一个类CssSyntaxError的实例,并向此方法传递的参数分配给错误实例。

错误实例将具有错误描述、节点在源中的原始位置、显示行号和列号。

如果存在任何先前的映射,它将用于获取源的原始位置。

此处的先前映射是指由先前编译生成的源映射,例如:Less、Stylus 和 Sass。

此方法返回错误实例,而不是抛出它。

if (!variables[name]) {
  throw decl.error(`Unknown variable ${name}`, { word: name })
  // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  //   color: $black
  // a
  //          ^
  //   background: white
}
参数类型描述
messagestring错误实例的描述。
optionsNodeErrorOptions错误实例的选项。

返回CssSyntaxError_

文档#every()

如果回调对容器的所有子项返回true,则返回true

const noPrefixes = rule.every(i => i.prop[0] !== '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

文档#index()

返回childContainer#nodes数组中的索引。

rule.index( rule.nodes[2] ) //=> 2
参数类型描述
child数字 | 当前容器的子项。

返回number

文档#insertAfter()

在容器中将新节点插入旧节点之后。

参数类型描述
oldNode数字 | 子项或子项的索引。
newNode字符串 | 字符串[] | 子属性 | 子属性[] | | []新节点。

返回 Document_

文档#insertBefore()

在容器中将新节点插入到旧节点之前。

rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
参数类型描述
oldNode数字 | 子项或子项的索引。
newNode字符串 | 字符串[] | 子属性 | 子属性[] | | []新节点。

返回 Document_

文档#next()

返回节点父级的下一个子级。如果当前节点是最后一个子级,则返回 undefined

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

返回 ChildNode

文档#nodes

包含容器子级的数组。

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

类型:[].

文档#parent

它表示当前节点的父级。

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

类型:未定义。

文档#positionBy()

获取节点内部某个单词或索引的位置。

参数类型描述
optsPick<WarningOptions, "index" | "word">选项。

返回 Position

文档#positionInside()

将字符串索引转换为行/列。

参数类型描述
indexnumber节点字符串中的符号数。

返回 Position

文档#prepend()

在容器开头插入新节点。

const decl1 = new Declaration({ prop: 'color', value: 'black' })
const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
rule.prepend(decl1, decl2)

root.append({ name: 'charset', params: '"UTF-8"' })  // at-rule
root.append({ selector: 'a' })                       // rule
rule.append({ prop: 'color', value: 'black' })       // declaration
rule.append({ text: 'Comment' })                     // comment

root.append('a {}')
root.first.append('color: black; z-index: 1')
参数类型描述
nodes…(string | string[] | Node | ChildProps | ChildProps[] | Node[])[]新节点。

返回 Document_

文档#prev()

返回节点父级的上一个子级。如果当前节点是第一个子级,则返回 undefined

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

返回 ChildNode

文档#push()

在节点末尾添加子级。

rule.push(new Declaration({ prop: 'color', value: 'black' }))
参数类型描述
childRoot新节点。

返回 Document_

文档#rangeBy()

获取节点内部某个单词或起始和结束索引的范围。起始索引包含在内;结束索引不包含在内。

参数类型描述
optsPick<WarningOptions, "index" | "word" | "endIndex">选项。

返回 Range

文档#raw()

返回 raws 值。如果节点缺少代码样式属性(因为节点是手动构建或克隆的),PostCSS 将尝试通过查看树中的其他节点来自动检测代码样式属性。

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
参数类型描述
propstring代码样式属性的名称。
defaultTypestring默认值的名称,如果值与 prop 相同,则可以省略。

返回 string

文档#raws

它表示 css 源代码中存在的不必要的空格和字符。

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

raws 对象的属性由解析器决定,默认解析器使用以下属性

PostCSS 会过滤选择器、声明值和 at 规则参数中的注释,但它会将原始内容存储在 raws 中。

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

类型:任意。

文档#remove()

它从其父级中移除节点并删除其父级属性。

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

返回 Document_

文档#removeAll()

从容器中移除所有子节点并清除其父级属性。

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

返回 Document_

文档#removeChild()

从容器中移除节点并清除节点及其子节点的父级属性。

rule.nodes.length  //=> 5
rule.removeChild(decl)
rule.nodes.length  //=> 4
decl.parent        //=> undefined
参数类型描述
child数字 | 子项或子项的索引。

返回 Document_

文档#replaceValues()

参数类型
patternstring | RegExp
replacedstring | Function
参数类型描述
patternstring | RegExp替换模式。
optionsValueOptions
replacedstring | Function

返回 Document_

文档#replaceWith()

在当前节点之前插入节点并移除当前节点。

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
参数类型描述
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]替换当前模式的模式。

返回 Document_

文档#root()

查找节点树的 Root 实例。

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

返回 Root

文档#some()

如果回调对容器的(至少)一个子节点返回 true,则返回 true

const hasPrefix = rule.some(i => i.prop[0] === '-')
参数类型描述
condition函数迭代器返回 true 或 false。

返回boolean

文档#source

它表示与节点的来源相关的信息,并且是生成源映射所必需的。

使用 PostCSS 提供的公共 API 手动创建的节点将具有未定义的 source,并且在源映射中将不存在。

出于此原因,插件开发人员应考虑复制节点,因为默认情况下复制的节点将与原始节点具有相同的源,或将源分配给手动创建的节点。

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

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

 atrule.parent.insertBefore(atrule, rule)
}

类型:Source

文档#toJSON()

修复 JSON.stringify() 上的循环链接。

返回 object

文档#toResult()

返回一个表示文档的 CSS 根的结果实例。

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 })
参数类型
optionsProcessOptions<Document_ | >

返回结果<Document_ | >

文档#toString()

根据其类型将节点编译为浏览器可读的层叠样式表字符串。

new Rule({ selector: 'a' }).toString() //=> "a {}"
参数类型描述
stringifierStringifier | Syntax<Document_ | Root>在字符串生成中使用的语法。

返回 string

文档#类型

它表示抽象语法树中节点的类型。

节点的类型有助于识别节点并根据其类型执行操作。

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

declaration.type //=> 'decl'

类型:“文档”。

文档#walk()

遍历容器的后代节点,为每个节点调用回调。

与 container.each() 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

如果您只需要遍历容器的直接子项,请使用 Container#each

root.walk(node => {
  // Traverses all descendant nodes.
})
参数类型描述
callback函数迭代器接收每个节点和索引。

返回void | false

文档#walkAtRules()

遍历容器的后代节点,为每个 at-rule 节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配名称的 at-rule 上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

root.walkAtRules(rule => {
  if (isOld(rule.name)) rule.remove()
})

let first = false
root.walkAtRules('charset', rule => {
  if (!first) {
    first = true
  } else {
    rule.remove()
  }
})
参数类型描述
nameFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

文档#walkComments()

参数类型
callback函数

返回void | false

文档#walkDecls()

遍历容器的后代节点,为每个声明节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配属性的声明上。

root.walkDecls(decl => {
  checkPropertySupport(decl.prop)
})

root.walkDecls('border-radius', decl => {
  decl.remove()
})

root.walkDecls(/^background/, decl => {
  decl.value = takeFirstColorFromGradient(decl.value)
})

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

参数类型描述
propFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

文档#walkRules()

遍历容器的后代节点,为每个规则节点调用回调。

如果您传递筛选器,则迭代只会发生在具有匹配选择器的规则上。

Container#each 一样,如果您在迭代期间对数组进行变异,则可以使用此方法。

const selectors = []
root.walkRules(rule => {
  selectors.push(rule.selector)
})
console.log(`Your CSS uses ${ selectors.length } selectors`)
参数类型描述
selectorFilterstring | RegExp
callback函数迭代器接收每个节点和索引。

返回void | false

文档#warn()

它是 Result#warn 的包装器,提供了生成警告的便捷方式。

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
参数类型描述
resultResult<Document_ | Root>将接收警告的 Result 实例。
messagestring警告的描述。
optionsWarningOptions警告的选项。

返回 Warning

fromJSON

参数类型
dataobject
参数类型
dataobject[]

返回 Node

input

输入#css

输入 CSS 源。

const input = postcss.parse('a{}', { from: file }).input
input.css //=> "a{}"

类型:字符串。

输入#error()

参数类型
messagestring
开始对象 | 对象
结束对象 | 对象
opts对象
参数类型
messagestring
linenumber
columnnumber
opts对象
参数类型
messagestring
偏移number
opts对象

返回CssSyntaxError_

输入#文件

使用from选项定义的 CSS 源文件的绝对路径。

const root = postcss.parse(css, { from: 'a.css' })
root.source.input.file //=> '/home/ai/a.css'

类型:字符串。

输入#fromOffset()

将源偏移转换为行和列。

参数类型描述
偏移number源偏移。

返回对象

输入#hasBOM

指示源代码是否有 Unicode BOM 的标志。

类型:布尔值。

输入#id

CSS 源的唯一 ID。如果未提供from选项,则会创建该 ID(因为 PostCSS 不知道文件路径)。

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

类型:字符串。

输入#map

从 PostCSS 之前的编译步骤(例如,来自 Sass 编译器)传递的输入源映射。

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

类型:PreviousMap_。

输入#origin()

读取输入源映射并返回输入源中的符号位置(例如,在传递给 PostCSS 之前编译为 CSS 的 Sass 文件中)。可以有选择地采用结束位置(不包括在内)。

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 }
参数类型描述
linenumber输入 CSS 中包含开始位置的行。
columnnumber输入 CSS 中包含开始位置的列。
endLinenumber输入 CSS 中排除结束位置的行。
endColumnnumber输入 CSS 中排除结束位置的列。

返回 false | FilePosition

延迟结果

延迟结果#async()

以异步方式运行插件并返回 Result

返回 Promise<Result<RootNode>>

延迟结果#catch

类型:函数。

延迟结果#finally

类型:函数。

延迟结果#sync()

以同步方式运行插件并返回 Result

返回 Result<RootNode>

延迟结果#then

类型:函数。

延迟结果#toString()

LazyResult#css 属性的别名。

lazy + '' === lazy.css

返回 string

延迟结果#warnings()

通过同步插件处理输入 CSS 并调用 Result#warnings

返回 Warning[]

无工作结果

无工作结果#async()

以异步方式运行插件并返回 Result

返回 Promise<Result<Root>>

无工作结果#catch

类型:函数。

无工作结果#finally

类型:函数。

无工作结果#sync()

以同步方式运行插件并返回 Result

返回 Result<Root>

无工作结果#then

类型:函数。

无工作结果#toString()

LazyResult#css 属性的别名。

lazy + '' === lazy.css

返回 string

无工作结果#warnings()

通过同步插件处理输入 CSS 并调用 Result#warnings

返回 Warning[]

node

节点#after()

在当前节点的父节点中将新节点插入到当前节点之后。

只是 node.parent.insertAfter(node, add) 的别名。

decl.after('color: black')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Node

节点#assign()

它将属性分配给现有的节点实例。

decl.assign({ prop: 'word-wrap', value: 'break-word' })
参数类型描述
overridesobject要覆盖节点的新属性。

返回 Node

节点#before()

在当前节点的父节点中将新节点插入到当前节点之前。

只是 node.parent.insertBefore(node, add) 的别名。

decl.before('content: ""')
参数类型描述
newNodestring | Node | ChildProps | Node[]新节点。

返回 Node

节点#cleanRaws()

清除节点及其子节点的代码样式属性。

node.raws.before  //=> ' '
node.cleanRaws()
node.raws.before  //=> undefined
参数类型描述
keepBetweenboolean保留 raws.between 符号。

节点#clone()

它创建现有节点的克隆,其中包括所有属性及其值,包括 raws 但不包括 type

decl.raws.before    //=> "\n  "
const cloned = decl.clone({ prop: '-moz-' + decl.prop })
cloned.raws.before  //=> "\n  "
cloned.toString()   //=> -moz-transform: scale(0)
参数类型描述
overridesobject在克隆中要覆盖的新属性。

返回 Node

节点#cloneAfter()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之后。

参数类型描述
overridesobject在克隆中要覆盖的新属性。

返回 Node

节点#cloneBefore()

克隆节点的快捷方式,并将生成的克隆节点插入到当前节点之前。

decl.cloneBefore({ prop: '-moz-' + decl.prop })
参数类型描述
overridesobject要在克隆中覆盖的新属性。

返回 Node

节点#error()

它创建一个类CssSyntaxError的实例,并向此方法传递的参数分配给错误实例。

错误实例将具有错误描述、节点在源中的原始位置、显示行号和列号。

如果存在任何先前的映射,它将用于获取源的原始位置。

此处的先前映射是指由先前编译生成的源映射,例如:Less、Stylus 和 Sass。

此方法返回错误实例,而不是抛出它。

if (!variables[name]) {
  throw decl.error(`Unknown variable ${name}`, { word: name })
  // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  //   color: $black
  // a
  //          ^
  //   background: white
}
参数类型描述
messagestring错误实例的描述。
optionsNodeErrorOptions错误实例的选项。

返回CssSyntaxError_

节点#next()

返回节点父级的下一个子级。如果当前节点是最后一个子级,则返回 undefined

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

返回 ChildNode

节点#parent

它表示当前节点的父级。

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

类型:容器_<子节点> | 文档_。

节点#positionBy()

获取节点内部某个单词或索引的位置。

参数类型描述
optsPick<WarningOptions, "index" | "word">选项。

返回 Position

节点#positionInside()

将字符串索引转换为行/列。

参数类型描述
indexnumber节点字符串中的符号数。

返回 Position

节点#prev()

返回节点父级的上一个子级。如果当前节点是第一个子级,则返回 undefined

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

返回 ChildNode

节点#rangeBy()

获取节点内部某个单词或起始和结束索引的范围。起始索引包含在内;结束索引不包含在内。

参数类型描述
optsPick<WarningOptions, "index" | "word" | "endIndex">选项。

返回 Range

节点#raw()

返回 raws 值。如果节点缺少代码样式属性(因为节点是手动构建或克隆的),PostCSS 将尝试通过查看树中的其他节点来自动检测代码样式属性。

const root = postcss.parse('a { background: white }')
root.nodes[0].append({ prop: 'color', value: 'black' })
root.nodes[0].nodes[1].raws.before   //=> undefined
root.nodes[0].nodes[1].raw('before') //=> ' '
参数类型描述
propstring代码样式属性的名称。
defaultTypestring默认值的名称,如果值与 prop 相同,则可以省略。

返回 string

节点#raws

它表示 css 源代码中存在的不必要的空格和字符。

生成与原始输入中完全相同的字节到字节的节点字符串的信息。

raws 对象的属性由解析器决定,默认解析器使用以下属性

PostCSS 会过滤选择器、声明值和 at 规则参数中的注释,但它会将原始内容存储在 raws 中。

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

类型:任意。

节点#remove()

它从其父级中移除节点并删除其父级属性。

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

返回 Node

节点#replaceWith()

在当前节点之前插入节点并移除当前节点。

AtRule: {
  mixin: atrule => {
    atrule.replaceWith(mixinRules[atrule.params])
  }
}
参数类型描述
nodes…(ChildNode | ChildProps | ChildNode[] | ChildProps[])[]替换当前模式的模式。

返回 Node

节点#root()

查找节点树的 Root 实例。

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

返回 Root

节点#source

它表示与节点的来源相关的信息,并且是生成源映射所必需的。

使用 PostCSS 提供的公共 API 手动创建的节点将具有未定义的 source,并且在源映射中将不存在。

出于此原因,插件开发人员应考虑复制节点,因为默认情况下复制的节点将与原始节点具有相同的源,或将源分配给手动创建的节点。

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

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

 atrule.parent.insertBefore(atrule, rule)
}

类型:Source

节点#toJSON()

修复 JSON.stringify() 上的循环链接。

返回 object

节点#toString()

根据其类型将节点编译为浏览器可读的层叠样式表字符串。

new Rule({ selector: 'a' }).toString() //=> "a {}"
参数类型描述
stringifierStringifier | Syntax<Document_ | Root>在字符串生成中使用的语法。

返回 string

节点#type

它表示抽象语法树中节点的类型。

节点的类型有助于识别节点并根据其类型执行操作。

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

declaration.type //=> 'decl'

类型:字符串。

节点#warn()

它是 Result#warn 的包装器,提供了生成警告的便捷方式。

  Declaration: {
    bad: (decl, { result }) => {
      decl.warn(result, 'Deprecated property: bad')
    }
  }
参数类型描述
resultResult<Document_ | Root>将接收警告的 Result 实例。
messagestring警告的描述。
optionsWarningOptions警告的选项。

返回 Warning

前一个映射

前一个映射#annotation

sourceMappingURL 内容。

类型:字符串。

前一个映射#consumer()

source-map 库创建 SourceMapGenerator 类的实例,以处理源映射信息。

这是一个惰性方法,因此它只会在第一次调用时创建对象,然后使用缓存。

返回 SourceMapConsumer

前一个映射#file

CSS 源标识符。如果用户设置了 from 选项,则包含 Input#file;如果用户没有设置,则包含 Input#id

类型:字符串。

前一个映射#inline

源映射是否通过 data-uri 内联到输入 CSS 中。

类型:布尔值。

前一个映射#mapFile

源映射文件的路径。

类型:字符串。

previous-map#

源映射文件的目录(如果源映射位于单独的文件中)。

类型:字符串。

previous-map#文本

源映射文件内容。

类型:字符串。

previous-map#withContent()

源映射是否包含带有输入源文本的 sourcesContent

返回boolean

stringifier

stringifier#atrule()

参数类型
nodeAtRule_
分号boolean

stringifier#beforeAfter()

参数类型
nodeAnyNode
检测"after" | "before"

返回 string

stringifier#block()

参数类型
nodeAnyNode
开始string

stringifier#body()

参数类型
nodeContainer_<子节点>

stringifier#builder

类型:Builder

stringifier#comment()

参数类型
nodeComment_

stringifier#decl()

参数类型
nodeDeclaration_
分号boolean

stringifier#document()

参数类型
nodeDocument_

stringifier#raw()

参数类型
nodeAnyNode
自身string
检测string

返回 string

stringifier#rawBeforeClose()

参数类型
rootRoot

返回 string

stringifier#rawBeforeComment()

参数类型
rootRoot
nodeComment_

返回 string

stringifier#rawBeforeDecl()

参数类型
rootRoot
nodeDeclaration_

返回 string

stringifier#rawBeforeOpen()

参数类型
rootRoot

返回 string

stringifier#rawBeforeRule()

参数类型
rootRoot

返回 string

stringifier#rawColon()

参数类型
rootRoot

返回 string

stringifier#rawEmptyBody()

参数类型
rootRoot

返回 string

stringifier#rawIndent()

参数类型
rootRoot

返回 string

stringifier#rawSemicolon()

参数类型
rootRoot

返回boolean

stringifier#rawValue()

参数类型
nodeAnyNode
propstring

返回 string

stringifier#root()

参数类型
nodeRoot

stringifier#rule()

参数类型
nodeRule

stringifier#stringify()

参数类型
nodeAnyNode
分号boolean