0
0
NextjsHow-ToBeginner · 3 min read

How to Use Sass in Next.js: Simple Setup and Example

To use Sass in Next.js, install sass via npm with npm install sass. Then, import your .scss or .sass files directly into your components or pages to apply styles.
📐

Syntax

In Next.js, you import Sass files just like CSS files. Use import './styles.scss' inside your component or page file. Sass files use .scss or .sass extensions. You write nested CSS and variables inside these files.

Example parts:

  • import './styles.scss': Loads the Sass styles.
  • .scss file: Contains Sass syntax like nesting and variables.
  • Next.js automatically compiles Sass to CSS during build.
javascript
import './styles.scss';

export default function Home() {
  return <div className="container">Hello with Sass!</div>;
}
Output
A page showing the text "Hello with Sass!" styled by the imported Sass file.
💻

Example

This example shows how to set up Sass in a Next.js project and use it to style a component with nested rules and variables.

javascript
// 1. Install Sass
// Run in terminal: npm install sass

// 2. Create styles.scss file
// styles.scss
$primary-color: #4caf50;

.container {
  padding: 1rem;
  background-color: $primary-color;
  color: white;
  border-radius: 0.5rem;

  h1 {
    font-size: 2rem;
    margin: 0;
  }
}

// 3. Use in component
// pages/index.js
import './styles.scss';

export default function Home() {
  return (
    <div className="container">
      <h1>Welcome to Next.js with Sass!</h1>
    </div>
  );
}
Output
A green box with white text "Welcome to Next.js with Sass!" styled by the Sass file with nested styles and variable color.
⚠️

Common Pitfalls

Common mistakes when using Sass in Next.js include:

  • Not installing sass package, so imports fail.
  • Using wrong file extensions like .css instead of .scss or .sass.
  • Forgetting to import the Sass file in the component or page.
  • Trying to use global styles without configuring globals.scss in pages/_app.js.

Always ensure sass is installed and files are imported correctly.

javascript
// Wrong: No sass installed
// import './styles.scss'; // This will error

// Right:
// npm install sass
// import './styles.scss';
📊

Quick Reference

Summary tips for using Sass in Next.js:

  • Install Sass with npm install sass.
  • Use .scss or .sass files for styles.
  • Import Sass files directly in components or pages.
  • For global styles, import Sass in pages/_app.js.
  • Use Sass features like variables, nesting, and mixins freely.

Key Takeaways

Install the sass package to enable Sass support in Next.js.
Import .scss or .sass files directly in your components or pages.
Use Sass features like variables and nesting to write cleaner styles.
For global styles, import Sass files in pages/_app.js.
Avoid missing imports or wrong file extensions to prevent errors.