@import in CSS, SCSS, and LESS

rohin bisht
2 min readDec 5, 2021

--

@import rule is present in CSS as well as popular preprocessor like SCSS, and LESS. So, what is the difference between them?

@import as the name suggests imports one stylesheet into another, so we can use mixins, functions, variables, or simply extend classes defined in that stylesheet.

CSS @import rule makes an HTTP call to fetch the resource from the path mentioned in @import url(<path>)
The biggest discouragement to using this is that CSS is itself a render-blocking resource and using multiple @import rules further halts the first render of the page.

Let’s discuss and compare @import in both SCSS and LESS.
When we have @import <file_path> in .scss or .less file it gets processed and all the styles inside the imported file replaces the @import statement.
So, clear advantage is that it doesn’t result in the @import rule in the compiled CSS.
Let’s do a quick experiment to make it clear. I will be using less preprocessor for this example.
Create two files a.less and test.less

// a.less.test-mixin() { color: red; }

.a-clss { color: green; }
// test.less@import './a.less';.test-class { .test-mixin(); }

Install less globally and run lessc ./test.less ./test.css

// test.css.a-clss { color: green; }.test-class { color: red; }

As, you can see we haven’t used a-clss in test.less but still it is there in compiled CSS. In SCSS behaviour is same, but there is a catch.
If we import a.scss more than once then in SCSS we will end up with duplicate styles resulting in bigger bundle sizes but in LESS we will have the styles only once.

To mitigate the issue of unused styles ending up in compiled CSS, in LESS we can use reference imports.
@import (reference) <file_path>

// test.less@import (reference) './a.less';.test-class { .test-mixin(); }

Now, we won’t get unused styles in compiled CSS

// test.css.test-class { color: red; }

SCSS has introduced a new keyword all together to handle duplicate imports issue. They encourage to use @use instead of @import in .scss files to avoid duplicate imported styles. For, omitting unsed styles in SCSS i don’t think they have anything yet comparable to the reference imports in LESS.

Both SCSS and LESS @import adds styles to global namespace. So style collosions might happen if a class or selector style in present in more than one stylesheet.

That’s all. Please comment and let me know if any correction is required in above information.

--

--

rohin bisht
rohin bisht

Written by rohin bisht

Clap if you like and Comment for any suggestions/corrections. Please subscribe as i will be posting articles on some interesting topics.

No responses yet