0

Need to make a head script tag with styles from CSS files-- how can I parse styles/style.css into a string to fill the documentStyles variable? This is happening in a Node.js function.

style.css

p {
  text-align: center;
}

index.js

const documentStyles = // SOMETHING TO STRINGIFY style.css

const document = `
  <!DOCTYPE html>
  <html>
    <head>
      <meta charset="UTF-8">
      <style>
        ${documentStyles}
      </style>
    </head>
    <body>
      <p>Here's the test</p>
    </body>
  </html>
`
user2521295
  • 823
  • 2
  • 12
  • 23

2 Answers2

1

You just have to load the contents of the CSS file using NodeJS fs.readFileSync.

const fs = require('fs');

try {  
  const documentStyles = fs.readFileSync('styles/style.css');
  const document = `
  <!DOCTYPE html>
  <html>
    <head>
      <meta charset="UTF-8">
      <style>
        ${documentStyles}
      </style>
    </head>
    <body>
      <p>Here's the test</p>
    </body>
  </html>
`;
} catch(e) {
    console.log('Error:', e.stack);
}
Christos Lytras
  • 36,310
  • 4
  • 80
  • 113
  • This solved it, thank you! I ended up having to use fs.readFileSync(path.resolve(__dirname, "styles/style.css")) to make it work, as I was getting an ENOENT error without using the path/__dirname. – user2521295 Jul 02 '20 at 16:18
1

It's pretty easy to get the string contents of a file in node via the file system (fs) module as Christos Lytras indicated, but if your concern is how to get an object that JavaScript can work with via an API, you probably want the CSSStyleSheet API.

This object has a .cssRules property which contains an array-like list of cssRule objects. You'll loop through these and check their type property (because different rule-types have different internal structures).

Most will have type: 1, which means they are cssStyleRule objects, which have:

  • a selector property (like .my-awesome-class), and
  • a style property (like { font-size: 1.5em; color: hotpink; }).

Once you get to this level, you might need to parse the selectors and styles with regex unless they're all pretty simple. You'll build a custom object to assign to your documentStyles variable.

Among other things, you'll want to convert CSS's kebab-case names to JavaScript's camelCase format (or you can probably find code on line that does it for you.)

(The answer to this question gives you an example of digging into a style sheet to find particulars rules and examine their style properties.)

Cat
  • 4,141
  • 2
  • 10
  • 18
  • Thank you for the thorough answer! This is great to know. For this particular case I just need to include it in the html string so Christos' response solved it. – user2521295 Jul 02 '20 at 16:17