使用ReworkCSS在CSS文件中添加注释



我正在尝试使用ReworkCSS解析器:

  1. 在CSS声明上面添加注释
  2. 注释掉一些CSS声明

我已经有了识别要注释/添加注释的声明的代码。只是想弄清楚如何在将AST渲染回CSS之前修改声明。

这是我在开头的一个代码示例:

@media screen and (min-width: 480px) {
body {
background-color: blue;
font-size:13px;
}
}
#main {
border: 1px solid black;
font-color: black;
}

经过处理后,我希望得到这样的结果。

@media screen and (min-width: 480px) {
body {
/* Case 1: add my comment here */
background-color: blue;
font-size:13px;
}
}
#main {
/* Case 2: border: 1px solid black; */
font-color: black;
}

终于找到了一个可以接受的解决方案。

我最初认为与每个声明(开始/结束)的行/列的位置对象会导致一个问题,由于数字不匹配(添加一行注释后,或添加额外的字符),但它看起来像reworkcss stringify专注于AST和忽略位置对象时呈现。

// Loop through declarations of a rule
if (rule.type == 'rule' && rule.declarations) {
let index = 0
rule.declarations?.forEach(function (dec) {
if (CONDITION TO ADD A COMMENT) {
// 1. Add a comment before the declaration dec
rule.declarations.splice(
index,
0,
{
type: 'comment',
comment: 'My comment'
})
}
// 2. Comment by replacing the type 'declaration' by 'comment', adding the 'comment' property and remmove the properties of the declaration
if (CONDITION TO COMMENT THE DECLARATION) {
dec.comment = dec.property + ': ' + dec.value,
dec.type = 'comment'
delete dec.property
delete dec.value
delete dec.position
}
index += 1
});
}

最新更新