BudiBadu Logo
Samplebadu

SCSS by Example: Imports

Sass 3.x+

Organizing stylesheets into modular files with this code example demonstrating partial files using underscore prefix, @import directive for file inclusion, modern @use rule with namespacing, and module system architecture.

Code

// _variables.scss (Partial)
$primary: blue;

// _mixins.scss (Partial)
@mixin reset {
  margin: 0;
  padding: 0;
}

// main.scss
// The underscore tells Sass not to compile the file individually
@import 'variables';
@import 'mixins';

// Newer module system (Dart Sass)
// @use 'variables';
// @use 'mixins';

body {
  @include reset;
  color: $primary;
}

Explanation

SCSS supports modular stylesheet architecture through partial files, which are named with a leading underscore like _variables.scss. The underscore signals to the Sass compiler that this file should not be compiled into a standalone CSS file but should only be included when imported. This allows large stylesheets to be split into logical, maintainable modules organized by concern such as variables, mixins, typography, or components.

The traditional @import directive includes the contents of a partial file at the location of the import statement. When importing, the underscore and file extension are optional, so @import 'variables'; will find _variables.scss. All imports are resolved at compile time, with the imported content being inserted directly into the importing file before CSS generation. This creates a single namespace where all variables, mixins, and functions from imported files are globally available.

Modern Sass implementations (Dart Sass) have introduced the @use and @forward rules to replace @import. The @use rule loads a module with a namespace, requiring explicit prefixing like variables.$primary to access members. This solves global namespace pollution issues and makes dependencies explicit. The @forward rule allows a file to make another module's members available to files that @use it, enabling the creation of public APIs for style libraries. These module system features provide better encapsulation and dependency management compared to the global nature of @import.

Code Breakdown

1
Underscore prefix in _variables.scss marks file as partial for import only.
12
@import 'variables'; includes _variables.scss content at this location.
16
@use loads module with namespace, requiring variables.$primary syntax.
20
Imported mixins and variables are available in global namespace with @import.