Skip to main content

Sass

Next.js 内置支持在使用 .scss.sass 扩展安装包后与 Sass 集成。你可以通过 CSS 模块和 .module.scss.module.sass 扩展使用组件级 Sass。

¥Next.js has built-in support for integrating with Sass after the package is installed using both the .scss and .sass extensions. You can use component-level Sass via CSS Modules and the .module.scssor .module.sass extension.

首先,安装 sass

¥First, install sass:

npm install --save-dev sass

很高兴知道:

¥Good to know:

Sass 支持 两种不同的语法,每个都有自己的扩展。.scss 扩展要求你使用 SCSS 语法,而 .sass 扩展要求你使用 缩进语法 ("Sass")

¥Sass supports two different syntaxes, each with their own extension. The .scss extension requires you use the SCSS syntax, while the .sass extension requires you use the Indented Syntax ("Sass").

如果你不确定选择哪个,请从 .scss 扩展开始,它是 CSS 的超集,并且不需要你学习缩进语法 ("Sass")。

¥If you're not sure which to choose, start with the .scss extension which is a superset of CSS, and doesn't require you learn the Indented Syntax ("Sass").

自定义 Sass 选项

¥Customizing Sass Options

如果你想配置 Sass 选项,请在 next.config 中使用 sassOptions

¥If you want to configure your Sass options, use sassOptions in next.config.

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
sassOptions: {
additionalData: `$var: red;`,
},
}

export default nextConfig
/** @type {import('next').NextConfig} */

const nextConfig = {
sassOptions: {
additionalData: `$var: red;`,
},
}

module.exports = nextConfig

实现

¥Implementation

你可以使用 implementation 属性指定要使用的 Sass 实现。默认情况下,Next.js 使用 sass 包。

¥You can use the implementation property to specify the Sass implementation to use. By default, Next.js uses the sass package.

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
sassOptions: {
implementation: 'sass-embedded',
},
}

export default nextConfig
/** @type {import('next').NextConfig} */

const nextConfig = {
sassOptions: {
implementation: 'sass-embedded',
},
}

module.exports = nextConfig

Sass 变量

¥Sass Variables

Next.js 支持从 CSS 模块文件导出的 Sass 变量。

¥Next.js supports Sass variables exported from CSS Module files.

例如,使用导出的 primaryColor Sass 变量:

¥For example, using the exported primaryColor Sass variable:

$primary-color: #64ff00;

:export {
primaryColor: $primary-color;
}
// maps to root `/` URL

import variables from './variables.module.scss'

export default function Page() {
return <h1 >Hello, Next.js!</h1>
}