About the @import Rule in CSS
I have previously mentioned my effort to move away from compiled CSS (using SASS) toward plain CSS. CSS has become capable enough that most of what used to require SASS can now be done without it. This eliminates a dependency in my front-end development toolset.
One challenge I failed to consider until today is the difference between the use of the @import
rule when using SASS versus CSS. This difference is summed up quite nicely by a StackOverflow post I found:
@import in CSS: CSS has an import option that lets you split your CSS into smaller, more maintainable portions.
Whereas,
@import in SASS/SCSS: Sass builds on top of the current CSS @import but instead of requiring an HTTP request, Sass will take the file that you want to import and combine it with the file you’re importing into so you can serve a single CSS file to the web browser.
This has implications for website performance. Say I created a style.scss file that has 10 @import
statements that bring in other SASS/SCSS files to be part of the compiled stylesheet. When the compiler processes this file, the code from all 10 external files will be pulled in and processed along with the code from style.scss, resulting in an single style.css file that no longer has any @import
statements.
Now say I have a CSS file with 10 @import
statements. When that file is loaded by a browser, it must then load 10 additional CSS files in order to render the page. Numerous articles and posts online recommend against using @import
in CSS. In terms of browser performance, CSS is a render-blocking resource. The more CSS files to load, the longer it will take to render the page.
So how do I solve this? I still want the organizational benefits of separating my style code into separate files, but I don’t want to use a SASS compiler. One solution would be to incorporate separate stylesheets by using the <link>
tag in HTML. According to various sources, linking multiple stylesheets to an HTML in this way allows the stylesheets to be loaded in parallel instead of one at a time. But what if I have a large design system with many components and one stylesheet per component. That could be many <link>
tags on each page.
So I guess I still need some sort of processing to convert component CSS files into a master CSS file.
Fortunately, Google Gemini was able to provide me a node.js script that will do this for me. Gemini didn’t give me the right regular expression for identifying the @import
rules in a stylesheet, so I had to use the Regex Tester to fix it, but most of the code was correct. The script will:
- read an input CSS file;
- find all the
@import
rules - read the files identified in each of those rules
- replace each
@import
rule with the code from the identified file - save the resulting CSS
The code even handles @import
rules where the imported code is assigned to a CSS cascade layer!