Currently, I am working on a substantial JavaScript-heavy application. Various pieces of JavaScript are associated with specific CSS rules. The norm right now is for each JavaScript file to have an optional related CSS file, following this pattern:
MyComponent.js // Adds CSS class "my-comp" to div
MyComponent.css // Defines .my-comp { color: green }
This method ensures that all CSS related to MyComponent.js
will be within MyComponent.css
.
However, I often find that these CSS files contain very little styling. And sometimes, it feels like too much effort to create a separate file just for a few lines of CSS - it might be simpler to hardcode the styles directly into the JavaScript. But that could lead down a risky path...
Lately, I've been contemplating the idea of embedding CSS directly within the JavaScript code - making it possible to extract during the build process and merge into one consolidated CSS file. This approach would eliminate the need to create a new file for every small piece of CSS. Additionally, if I move/rename/delete the JavaScript file, I wouldn't have to separately handle the CSS file.
But how can CSS be embedded within JavaScript? In many other languages, using a string would suffice, but JavaScript presents some challenges with multiline strings. The following method appears somewhat unattractive in my opinion:
Page.addCSS("\
.my-comp > p {\
font-weight: bold;\
color: green;\
}\
");
What alternative practices do you employ to ensure your JavaScript and CSS stay synchronized?