What is the @import rule in Sass
Just like CSS, Sass also supports the @import directive, which allows the inclusion of one stylesheet in another. As an extension to the CSS @import rule, the Sass @import rule allows importing .sass and .scss files. Moreover, if you are importing one stylesheet in another stylesheet then this rule will give access to variables, mixins, and functions of the imported file to the other file.
Another advantage that this Sass rule has over the CSS rule is that no additional HTTP request is made at run time when the @import rule is called.
Syntax
The Sass @import rule allows the inclusion of both types, which means you can include Sass files in a CSS file or you can import CSS files in a Sass file. Moreover, you can import as many files as you desire in the main file. Files that can be imported include reset files, colors, variables, fonts, etc.
Some examples of @import rule in Sass are as follows.
@import "variables";
@import "colors";
Let’s look at an example to understand this rule better.
Example
Suppose we have a file by the name file1.sass and it looks something like this.
Sass
font-family: Verdana, sans-serif;
font-size: 30px;
color: purple;
}
We also have another file by the name file2.sass and has the following code.
Sass
font-family: Times New Roman, serif;
font-size: 20px;
color: blue;
}
Now we want to import both of these files into another file having the name main.sass. We will use the @import rule to do so.
After compiling this main.sass file our resultant CSS output file will appear like this.
Files were successfully imported!
Note: The usage of the @import rule is discouraged because it causes naming conflicts as it gives access to all the functions, variables, mixins, etc to the other file. Moreover, this also causes security issues.
Partials in Sass
Partials in Sass are regarded as those files whose names start with an underscore and these are not transpiled directly. Partials are made only in those circumstances when you are importing a file and do not want your file to be transpiled directly by Sass.
Syntax
For instance, the file shown below is a “_font.scss” file.
$fontfamily: Times New Roman;
$color: blue;
The starting underscore prevents this file from transpiling to fonts.css. However, when you wish to import this file do not use the underscore.
@import "fonts"
h1 {
font-size: $fontsize;
text-align; center;
color: $color;
}
This way the partial sass file will be imported.
Conclusion
The Sass @import directive allows the inclusion of one stylesheet in another and gives access to variables, mixins, functions of the imported file to the other file. Moreover, no additional HTTP request is made at run time when the @import rule is called. Meanwhile, partials in Sass are regarded as those files whose names start with an underscore and these are not transpiled directly when you import them. Both of these entities are discussed in depth in this article.