CSS parser for JavaScript?

后端 未结 7 1088
既然无缘
既然无缘 2020-12-13 19:45

Update 2018: This question was asked long before PostCSS existed, and I would have probably used that.

I\'d like to par

7条回答
  •  半阙折子戏
    2020-12-13 20:14

    Update: I previously mentioned JSCSSP, which is buggy seems to be abandoned. Obviously enough, the css module on NPM is the best:

    css = require 'css'
    
    input = '''
      body {
        font-family: sans-serif;
      }
      #thing.foo p.bar {
        font-weight: bold;
      }
    '''
    
    obj = css.parse input
    sheet = obj.stylesheet
    
    for rule in sheet.rules
      rule.selectors = ('#XXX ' + s for s in rule.selectors)
    
    console.log css.stringify(obj)
    

    Output:

    #XXX body {
      font-family: sans-serif;
    }
    #XXX #thing.foo p.bar {
      font-weight: bold;
    }
    

提交回复
热议问题