乐闻世界logo
搜索文章和话题

How to implement Global Styles in NextJS with SCSS?

1个答案

1
  1. Install Dependencies

You first need to install sass. You can install it using npm or yarn:

bash
npm install sass

or

bash
yarn add sass
  1. 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
  1. Import the Global SCSS File in _app.js or _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.

  1. 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).

2024年6月29日 12:07 回复

你的答案