Sass Variables and Importing Other Files
Same file sass variables
There may be times when it makes sense to add variables in the same file that consumes them. This is mostly relevant for variables that will only be used in one file and will need to be used multiple times there. For example, we can take a look at this scss file
// chart.scss
$chart-text-color: rgb(255, 0, 0);
.chart-header {
color: $chart-text-color;
}In this example, we create the variable chart-text-color and then immediately consume it. For more information about Sass variables, please see their official documentation.
Importing files in sass
With Sass, we are able to use many pre-defined rules that allow for extra functionality. One of these is @use which allows us to combine stylesheets. This is important for when some base styles are available in one sheet and should be used in multiple places.
For example, we can look at these two stylesheets in the same directory:
// chartBase.scss
.chart-subtitle {
color: rgb(0, 0, 0);
font-size: 16px;
}// timeseriesChart.scss
@use 'chartBase';
.chart-timeseries-time {
font-size: 12px
}In this example, a component that only imports the timeseriesChart.scss file will get the styles from both chartBase.scss and timeseriesChart.scss without having to repeat the styles in both files.
Cross file sass variables
Another use case for @use rule is to provide variables across files. @use creates the variables in a way that requires namespacing in order to use them. This allows developers to use simple variable names and ensure they are always using the correct variable.
For example, we can go back to the chart scss:
// chartBase.scss
$chart-font-size: 16px;
.chart-subtitle {
color: rgb(0, 0, 0);
font-size: $chart-font-size;
}// timeseriesChart.scss
@use 'chartBase';
.chart-timeseries-time {
font-size: chartBase.$chart-font-size;
}Here we define and use the variable chart-font-size in chartBase.scss, and we then are able to use the same variable in timeseriesChart.scss. You can read more about this works with the loading members section of the @use documentation.