SASS - use variables across multiple files
I would like to keep one central .scss file that stores all SASS variable definitions for a project.
// _master.scss
$accent: #6D87A7;
$error: #811702;
$warning: #F9E055;
$valid: #038144;
// etc...
The project will have a large number of CSS files, due to its nature. It is important that I declare all project-wide style variables in one location.
Is there a way to do this in SCSS?
Solution 1:
You can do it like this:
I have a folder named utilities and inside that I have a file named _variables.scss
in that file i declare variables like so:
$black: #000;
$white: #fff;
then I have the style.scss file in which i import all of my other scss files like this:
// Utilities
@import "utilities/variables";
// Base Rules
@import "base/normalize";
@import "base/global";
then, within any of the files I have imported, I should be able to access the variables I have declared.
Just make sure you import the variable file before any of the others you would like to use it in.
Solution 2:
This question was asked a long time ago so I thought I'd post an updated answer.
You should now avoid using @import
. Taken from the docs:
Sass will gradually phase it out over the next few years, and eventually remove it from the language entirely. Prefer the @use rule instead.
A full list of reasons can be found here
You should now use @use
as shown below:
_variables.scss
$text-colour: #262626;
_otherFile.scss
@use 'variables'; // Path to _variables.scss Notice how we don't include the underscore or file extension
body {
// namespace.$variable-name
// namespace is just the last component of its URL without a file extension
color: variables.$text-colour;
}
You can also create an alias for the namespace:
_otherFile.scss
@use 'variables' as v;
body {
// alias.$variable-name
color: v.$text-colour;
}
EDIT As pointed out by @und3rdg at the time of writing (November 2020) @use
is currently only available for Dart Sass and not LibSass (now deprecated) or Ruby Sass. See https://sass-lang.com/documentation/at-rules/use for the latest compatibility