2

I am attempting to modify CSS as part of a Node JS build process, but most of what I can find online refers to doing this in the DOM with Javascript. Is it possible to read a file in Node and access the equivalent of document.stylesheet or the cssRules property or is this a DOM-only concept and I need to stick with string replacement to modify these CSS rules/properties?

For reference here is the browser-based answer to the problem I'm trying to solve: How do you read CSS rule values with JavaScript?

atjohns2
  • 57
  • 7
  • You can do it by doing the same sort of text replacement on it that people [often do with Javascript](https://www.npmjs.com/package/@rollup/plugin-replace). What exactly are you trying to achieve? Why are you modifying styles at *build* time? – Jared Smith Jun 05 '23 at 18:15
  • Yes, it's possible to implement the CSSOM in nodejs. Are you looking for a library that has already done it? – Bergi Jun 05 '23 at 21:13
  • Yep that was what I was looking for, I think the JSDOM is going to do the trick from the answer below but thanks for responding. – atjohns2 Jun 06 '23 at 16:10
  • Actually @Bergi JSDOM seems designed for HTML much moreso than CSS so if you have a recommendation for another library I'd love to check it out. – atjohns2 Jun 07 '23 at 17:59

1 Answers1

0

I think there's nothing bad to manipulate CSS with DOM, use for that: https://www.npmjs.com/package/jsdom

For manipulate CSS directly you could parse it into AST:
https://www.npmjs.com/package/css-tree

CSSTree is a tool set for CSS: fast detailed parser (CSS → AST), walker (AST traversal), generator (AST → CSS) and lexer (validation and matching) based on specs and browser implementations. The main goal is to be efficient and W3C spec compliant, with focus on CSS analyzing and source-to-source transforming tasks.

Alexander Nenashev
  • 8,775
  • 2
  • 6
  • 17