Postss8插件:如何避免循环到Declaration函数



邮政编码专家您好!

我正在更新一个旧的插件到postCSS 8 API,但我遇到了一些问题。

这个简单的postCSS插件陷入了一个无限循环:

module.exports = (options = {}) => {
return {
postcssPlugin: 'postcss-failing-plugin',
Declaration(decl) {
if (decl.prop.startsWith('--')) {
decl.prop = decl.prop.replace(/^--/, `--prefix-`);
}
},
};
};
module.exports.postcss = true;

文件中提到了这种行为:

插件将重新访问您更改或添加的所有节点。如果您要更改任何子项,插件也将重新访问父项。只有OnceOnceExit将不再被调用。编写插件

但没有什么可以避免的。

如何在不进行无限循环的情况下编辑Declaration中的值?

您可能会重复向已加前缀的自定义属性声明添加前缀,从而导致声明访问者无限运行。

您可以使用负前瞻断言(?!)来匹配没有以特定自定义属性前缀(即^--(?!prefix-)(开头的自定义属性。

const matcher = /^--(?!prefix-)/
const replacement = '--prefix-'
const ensure = value => value.replace(matcher, replacement)
// these _should not_ receive a new prefix
ensure('foo')          // "foo"
ensure('prefix-foo')   // "prefix-foo"
ensure('--prefix-foo') // "--prefix-foo"
// these _should_ receive a new prefixed
ensure('--foo')            // "--prefix-foo"
ensure('--prefixable-foo') // "--prefix-prefixable-foo"

应用于您的示例

module.exports = (options = {}) => {
return {
postcssPlugin: 'postcss-failing-plugin',
Declaration(decl) {
/** Matches a `--` property not beginning with `--prefix-`. */
const match = /^--(?!prefix-)/
if (match.test(decl.prop)) {
decl.prop = decl.prop.replace(match, `--prefix-`);
}
},
};
};
module.exports.postcss = true;

相关内容

最新更新