Add Comment in a CSS file with ReworkCSS

37 views Asked by At

I am trying to use ReworkCSS parser to either:

  1. add comment above a CSS declaration
  2. comment out some CSS declaration

I already have the code to identify the declarations to comment / add comment to. Just trying to figure out how to modify the declaration before rendering the AST back into CSS.

This is an example of code I have at the beginning:

@media screen and (min-width: 480px) {
    body {
        background-color: blue;
        font-size:13px;
    }
}

#main {
    border: 1px solid black;
    font-color: black;
}

After processing, I would like to get something like this.

@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;
}
1

There are 1 answers

0
Jeremie On BEST ANSWER

Finally found an acceptable solution.

I was initially thinking that the position object with the line/column of each declaration (start/end) would cause a problem due to the numbers not matching (after adding a line with comment, or adding extra characters), but it looks like that reworkcss stringify focuses on the AST and ignores the position objects when rendering.

// 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

        });
      }