- Install Dependencies
You first need to install sass. You can install it using npm or yarn:
bashnpm install sass
or
bashyarn add sass
- Create a Global SCSS File
Create a SCSS file in your project, typically placed in the styles folder. For example, you can create a file named globals.scss.
scss// styles/globals.scss // Global styles body { margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; } // Other global styles
- Import the Global SCSS File in
_app.jsor_app.tsx
Open the _app.js or _app.tsx file in the pages directory and import your global SCSS file at the top of the file:
javascript// pages/_app.js or pages/_app.tsx import '../styles/globals.scss' function MyApp({ Component, pageProps }) { return <Component {...pageProps} /> } export default MyApp
This ensures that the global styles are applied throughout your application.
- Using CSS Modules
If you need to use SCSS in specific components, create a modular SCSS file. For example, ComponentName.module.scss. Then import it in your component and use the styles as an object.
scss// components/ComponentName.module.scss .example { color: blue; }
Using it in the component:
javascript// components/ComponentName.js or components/ComponentName.tsx import styles from './ComponentName.module.scss'; function ComponentName() { return <div className={styles.example}>This is blue text.</div>; } export default ComponentName;
Note that starting from Next.js 9.3, Next.js has built-in Sass support, so you don't need additional plugins for SCSS files. However, node-sass is no longer recommended from Next.js 10 onwards, as it has been deprecated and replaced by sass (Dart Sass).