Blog>
Snippets

Enhancing Performance with Sass's @forward Rule in Next.js

Discuss how to use Sass's @forward rule to enable partials to forward styles and mixins to other stylesheets, improving organization and performance in a Next.js application.
// styles/_variables.scss
$primary-color: #333;
$font-stack: Helvetica, sans-serif;
This is a partial file named _variables.scss that contains Sass variables to be reused across the application. The underscore indicates it's a partial.
// styles/_mixins.scss
@forward 'variables';

@mixin font-stack { font-family: $font-stack; }
@mixin primary-color { color: $primary-color; }
In _mixins.scss, we use the @forward rule to make variables from _variables.scss available. We then define some mixins that use these variables.
// styles/main.scss
@forward 'mixins';

body { @include font-stack; background-color: $primary-color; }
In main.scss, we forward styles from _mixins.scss using @forward, giving us access to mixins that we then apply to the body selector along with a variable.
// pages/index.jsx
import '../styles/main.scss';

export default function Home() {
  return <div>Welcome to my Next.js app!</div>;
}
In the index.jsx page component of our Next.js app, we import main.scss to apply the styles defined there. This showcases how to use Sass files in Next.js components.