CSS
Which Directive is Used to Convert Multiple SASS Files into Single or Multiple CSS Files?
SASS (Syntactically Awesome Stylesheets) is a powerful preprocessor that enhances CSS by introducing variables, nesting, mixins, and modularity. When working on large projects, developers often split styles into multiple SASS files for better organization. But how do we compile multiple SASS files into a single or multiple CSS files?
The answer lies in the @import
and @use
directives.
1. Using @import
(Deprecated in Newer Versions)
In older versions of SASS, the @import
directive was widely used to combine multiple SASS files into a single CSS file.
Example: Importing Multiple SASS Files into One CSS File
π Folder Structure:
/styles
βββ main.scss
βββ _header.scss
βββ _footer.scss
βββ _buttons.scss
π Main SASS File (main.scss):
@import 'header';
@import 'footer';
@import 'buttons';
β When compiled, main.scss
generates a single main.css
file containing all styles.
Why @import
is No Longer Recommended?
- It slows down compilation by processing each imported file separately.
- It causes redundancy because styles can be included multiple times.
- It does not support scoped modules, leading to global namespace pollution.
Thatβs why SASS introduced @use
as a better alternative!
2. Using @use
(Recommended in Modern SASS)
The @use
directive is now the preferred way to import and compile multiple SASS files efficiently.
Example: Importing Multiple SASS Files Using @use
π Main SASS File (main.scss):
@use 'header';
@use 'footer';
@use 'buttons';
β When compiled, main.scss
produces a single CSS file like before, but with better performance and modularity.
Key Benefits of @use
Over @import
β
No duplicate CSS β Ensures styles are included only once.
β
Encapsulation β Variables and mixins stay inside their respective modules.
β
Improved performance β Faster compilation due to module-based processing.
3. Compiling Multiple SASS Files into Separate CSS Files
If you need multiple separate CSS files, compile each SASS file independently using the command line:
sass styles/header.scss styles/header.css
sass styles/footer.scss styles/footer.css
sass styles/buttons.scss styles/buttons.css
Alternatively, for automatic compilation, you can use a package.json
script with Node.js:
"scripts": {
"sass": "sass styles/main.scss styles/main.css --watch"
}
β This watches for changes and compiles only the affected files.
Conclusion
To compile multiple SASS files into CSS:
β Use @use
(instead of @import
) to merge multiple SASS files into one CSS file.
β Use command-line compilation to generate separate CSS files.
β Avoid @import
in modern SASS as it’s inefficient and outdated.