csssass

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

  • 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:

    As of Dart Sass 1.80.0, the @import rule is deprecated and will be removed from the language in Dart Sass 3.0.0. 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