Blog>
Snippets

Utilizing Sass @use Rule for Better Dependency Management

Demonstrate the power of the Sass @use rule in a Next.js project for managing dependencies between stylesheets, allowing for better encapsulation and namespace control.
// 1. Install Sass
import 'sass';
First, ensure that the sass package is installed in the Next.js project for compiling Sass files.
// 2. Create a Sass file (variables.scss) to store variables
$primary-color: #ff473e;
$secondary-color: #37474f;
Set up a Sass file (variables.scss) with some variables that can be used throughout the project.
// 3. Create another Sass file (mixins.scss) with mixins
@mixin flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}
Create a separate Sass file (mixins.scss) to hold common mixins that can be reused.
// 4. Use the @use rule in a component's Sass file (component.scss)
@use 'variables' as vars;
@use 'mixins';

.component {
  color: vars.$primary-color;
  @include mixins.flex-center;
}
In the component's Sass file (component.scss), use the @use rule to import variables and mixins, using them with namespaces.
// 5. Import the component Sass file in the Next.js component
import styles from './component.module.scss';

function MyComponent() {
  return <div className={styles.component}>My Styled Component</div>;
}
In the Next.js component file, import the component's module.scss, which applies the styles written using Sass variables and mixins.