使用 Node JS 将 CSS 拆分为 2 个 CSS 文件并返工

splitting css into 2 css files using node js and rework

本文关键字:CSS 文件 Node JS 拆分 使用      更新时间:2023-09-26

如何将一个 CSS 文件拆分为两个,例如:使用 Node JS 和 reworkcss/CSS 生成以下形式的 2 个输出https://github.com/reworkcss/css

main.css
 body{
        color: blue;
        font-size: 12px;
        background-color: red;
 }
 h1 , div{
        color: red;
 }
 output1.css
 body{
        font-size: 12px;
        background-color: red;
 }
 output2.css
 body{
        color: blue;
 }
 h1 , div{
        color: red;
 }

使用两个 ast 文件,一个用于 font-sizebackground-color

{
  "type": "stylesheet",
  "stylesheet": {
    "rules": [
      {
        "type": "rule",
        "selectors": [*],
        "declarations": [
          {
            "type": "declaration",
            "property": "font-size",
            "value": "",
            "position": {
              "start": {
                "line": 1,
                "column": 1
              },
              "end": {
                "line": 99,
                "column": 99
              },
              "source": "input.css"
            }
          },
          {
            "type": "declaration",
            "property": "background-color",
            "value": "",
            "position": {
              "start": {
                "line": 1,
                "column": 1
              },
              "end": {
                "line": 99,
                "column": 99
              },
              "source": "input.css"
            }
        ],
        "position": {
          "start": {
            "line": 1,
            "column": 1
          },
          "end": {
            "line": 99,
            "column": 99
          },
          "source": "input.css"
        }
      }
    ]
  }
}

另一个用于其余的:

{
  "type": "stylesheet",
  "stylesheet": {
    "rules": [
      {
        "type": "rule",
        "selectors": [*],
        "declarations": [
          {
            "type": "declaration",
            "property": "color",
            "value": "",
            "position": {
              "start": {
                "line": 1,
                "column": 1
              },
              "end": {
                "line": 99,
                "column": 99
              },
              "source": "input.css"
            }
          }
        ],
        "position": {
          "start": {
            "line": 1,
            "column": 1
          },
          "end": {
            "line": 99,
            "column": 99
          },
          "source": "input.css"
        }
      }
    ]
  }
}

引用

  • Reworkcss 测试用例:选择器 - ast.json

  • 自定义 CSS 预处理 – Nicolas Gallagher