我可以 运行 postcss 插件直接针对 postcss 结果对象吗?

Can I run postcss plugins directly against a postcss Result object?

根据 the postcss docs,我应该能够对 postcss Result 对象执行插件,就像我对 CSS(使用 Processor.process)。

不幸的是,这似乎不起作用。我已经演示了这个 "bug" here (为了方便,我还复制了下面的代码)。只需单击 link,打开浏览器的控制台,然后单击 "Run Code" 即可执行测试。

我的问题是:既然这行不通,我如何 运行 一个 postcss 插件直接针对 postcss Result 对象?


演示问题的测试代码

首先,我需要 postcss、一个插件和一个测试工具

var postcss = require('postcss')
var cssnext = require('postcss-cssnext')
var test = require('tape')

接下来我定义了一些输入 css 和我期望 运行 插件

的输出
var input = 'body { color: rebeccapurple; }'
var expected = 'body { color: rgb(102, 51, 153); }'

现在,测试本身:

1:正常使用,证明插件正常工作

test('cssnext', function (t) {
  t.plan(1)
  postcss([cssnext]).process(input).then(function (result) {
    t.equals(result.css, expected, 'produces the expected result')
  })
})

此测试通过:

ok 1 produces the expected result

2:使用文档中定义的方法直接在Result对象上应用插件

test('running plugins against a Result object (1)', function (t) {
  t.plan(1)
  // first run without plugins to get a Result object
  postcss([]).process(input).then(function (result) {
    postcss([cssnext]).process(result)
      .then(function () {
        t.equals(result.css, expected, 'produces the same result')
      })
  })
})

此测试失败:

not ok 2 produces the same result
   ---
     operator: equal
     expected: |-
       'body { color: rgb(102, 51, 153); }'
     actual: |-
       'body { color: rebeccapurple; }'
   ...

3:又一次尝试,手动执行插件功能

test('running plugins against a Result object (2)', function (t) {
  t.plan(1)
  // first run without plugins to get a Result object
  postcss([]).process(input).then(function (result) {
    Promise.resolve(cssnext(result.root, result))
      .then(function () {
        t.equals(result.css, expected, 'produces the same result')
      })
  })
})

这个测试也失败了:

not ok 3 produces the same result
   ---
     operator: equal
     expected: |-
       'body { color: rgb(102, 51, 153); }'
     actual: |-
       'body { color: rebeccapurple; }'
   ...

您在测试 2 中遇到问题 — 您忘记在第二个 process 调用中获取第二个 result 参数。正确测试:

test('running plugins against a Result object (1)', function (t) {
  t.plan(1)
  // first run without plugins to get a Result object
  postcss([]).process(input).then(function (result) {
    postcss([cssnext]).process(result)
      .then(function (result2) {
        t.equals(result2.css, expected, 'produces the same result')
      })
  })
})

测试 3 中的问题是 result.css 不是一个神奇的东西。如果您要更改 result.root,它不会更新 result.css。这是一个可能的解决方案:

result.css = result.root.toString()