Using @import in CSS pre-processors with Care
Inspired by CSS’s @import feature which imports style rules from other style sheets, popular CSS pre-processors like Sass, Less and Stylus all have their own @import directives. They are powerful ways to start putting together modular stylesheets using variables, mixins and other features of each pre-processors. To use them properly we should:
Take great care when using @import directives:
By default, Sass, Less and Stylus output any selectors declared in the imported files when generating the CSS.

Careless imports often lead to bloated, wasted CSS
Let’s take a look at this example file intend to generate 3 classes:
With the imported typography module being:
The actual output includes many more classes then we intended to generate:
This gets worse when @import are used carelessly
CSS Output:
It ends up having a lot more CSS than I needed. I only wanted to import external files by references and intend to output only what was declared in the current file. 😢 Careless imports often lead to bloated, wasted CSS in application bundles, creating unnecessary load on the clients. The confusing output could also make debugging harder especially when the unexpected output from one file overrides the classes of another. This leads to the question:
How to import by reference only
Less users, you are in luck! @import (reference) does exactly what it that:
Use
@import (reference)
to import external files, but without adding the imported styles to the compiled output unless referenced.
However in Stylus /Sass, there is no direct way to import by reference:
The closest you will get is a silent class / placeholder. These work a little different to how LESS and reference work, you can read more on them here: http://blog.teamtreehouse.com/extending-placeholder-selectors-with-sass
You can do the following in Stylus/Sass:
- Organize your variables and placeholders in files separate from sources of declared selectors intended for final outputs.
- Try importing only from sources of variables/placeholders and with the almighty @extend directive, you can inherit and compose everything you need
- Only import from sources of declared selectors for building rollups
The first example would look something like this in Sass:
With these organizational tips, you will start seeing less bloated and wasted CSS output in your app bundles, and your style source will also become more modular, composable and maintainable over time!
Let me know if there are any other good tips around @import for Stylus/Sass. Happy styling!
Full disclaimer: I wrote this original draft of this as an internal post when I worked at drift.com more than a year ago. Since then I have been doing most of my UI development in React and found great success maintaining styling using inline style solutions and styled-jsx for full, scoped and component-friendly CSS support for JSX