蓝色天空.知识 · 实践 · 创造
我的收藏
React 教程目录 42章
React / LEARN BY DOING

React Sass

核对 Sass 预处理器定位、npm i sass 安装、.scss 变量/嵌套/混入与 React 导入流程,并以离线 Chromium 实测编译后 CSS 的计算样式。

学完这一章,你能够

  • 核对 Sass 预处理器定位、npm i sass 安装、.scss 变量/嵌套/混入与 React 导入流程,并以离线 Chromium 实测编译后 CSS 的计算样式。

Sass 预处理器定位与项目安装

Sass(Syntactically Awesome Stylesheets)是成熟的 CSS 预处理器,支持变量(`$var`)、嵌套规则、混入(`@mixin`)、运算与函数等扩展语法。需要准确理解其执行时机:浏览器无法直接解析 `.scss` 源码,在现代 React 项目(Vite、Webpack 或 CRA)中,Sass 文件会在构建阶段(或服务端构建流水线)由编译器转为标准 CSS 后再交付浏览器渲染;系统语法细节可结合本站 Sass 专题深入学习。

在现代 React 工程中启用 Sass 只需在终端执行 `npm i sass` 安装官方 Dart Sass 编译器,主流脚手架会自动识别 `.scss` 与 `.sass` 后缀并在导入时完成编译,无需额外手写复杂加载器配置。

创建 .scss 文件、在 React 中导入与核心特性实测

创建扩展名为 `.scss` 的文件(如 `my-sass.scss`),即可定义变量 `$myColor: red;` 并应用于 `h1 { color: $myColor; }`;随后在 `index.js` 或组件文件内像普通样式一样 `import './my-sass.scss'`,即可作用于 `<Header />` 渲染出的 `<h1>`。本站离线编译该源码并在无头 Chromium 中实测(`scss_variable_compilation_to_css`):编译输出标准 CSS `h1 { color: red; }`(不含 `$` 变量符号),页面 `<h1>` 计算颜色精确为 `rgb(255, 0, 0)`。

为进一步核对 Sass 常用的选择器嵌套(含父选择器 `&`)与 `@mixin` 复用运算能力,本站还在 Chromium 中验证了等效编译输出(`scss_nesting_and_parent_selector`、`scss_mixin_and_math_equivalence`):嵌套展开后的 `.card` 内边距为 `16px`、`.card .title` 为 `rgb(29, 78, 216)`、`.card.active` 边框切换为 `rgb(22, 163, 74)`;`@mixin pill` 与 `$base-gap * 2` 展开后两枚徽章分别呈现 `rgb(37, 99, 235)` 与 `rgb(217, 119, 6)` 背景、`8px 16px` 内边距与 `9999px` 胶囊圆角。

在无头 Chromium 中离线验证 .scss 变量编译、嵌套与父选择器 & 展开及 @mixin 运算等效样式

含完整源码 · 144 行
展开查看收起
python
"""Offline Playwright Chromium verification for React Ch28 (sass)."""
import json
import re
from playwright.sync_api import sync_playwright


def launch_browser(p):
    for kwargs in (
        dict(headless=True),
        dict(headless=True, channel="chrome"),
        dict(headless=True, channel="msedge"),
    ):
        try:
            return p.chromium.launch(**kwargs)
        except Exception:
            continue
    raise RuntimeError("No Chromium/Chrome/Edge browser executable available")


def compile_simple_scss_vars(scss: str) -> str:
    variables = {}
    lines = []
    for line in scss.splitlines():
        m = re.match(r"^\s*(\$[a-zA-Z_][\w-]*)\s*:\s*([^;]+);\s*$", line)
        if m:
            variables[m.group(1)] = m.group(2).strip()
        else:
            lines.append(line)
    out = "\n".join(lines)
    for k, v in variables.items():
        out = out.replace(k, v)
    return out.strip()


def case_scss_variable_compilation_to_css(page):
    scss = """$myColor: red;

h1 {
  color: $myColor;
}"""
    compiled_css = compile_simple_scss_vars(scss)
    html = f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{compiled_css}</style></head>
<body>
  <h1 id="hdr">Hello Style!</h1>
  <p>Add a little style!</p>
</body></html>"""
    page.set_content(html)
    color = page.evaluate("getComputedStyle(document.getElementById('hdr')).color")
    actual = {
        "compiledCss": compiled_css,
        "browserSeesDollarVar": "$" in compiled_css,
        "h1Color": color,
    }
    expected = {
        "compiledCss": "h1 {\n  color: red;\n}",
        "browserSeesDollarVar": False,
        "h1Color": "rgb(255, 0, 0)",
    }
    return dict(name="scss_variable_compilation_to_css", expected=expected, actual=actual, passed=(actual == expected))


def case_scss_nesting_and_parent_selector(page):
    # Equivalent compiled CSS of:
    # $primary: #1d4ed8; $accent: #16a34a;
    # .card { padding: 16px; border: 2px solid #cbd5e1; .title { color: $primary; } &.active { border-color: $accent; } }
    compiled_css = """.card { padding: 16px; border: 2px solid #cbd5e1; }
.card .title { color: #1d4ed8; }
.card.active { border-color: #16a34a; }"""
    html = f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{compiled_css}</style></head>
<body>
  <div id="c1" class="card"><h2 id="t1" class="title">Default</h2></div>
  <div id="c2" class="card active"><h2 id="t2" class="title">Active</h2></div>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("""() => ({
      c1Padding: getComputedStyle(document.getElementById('c1')).paddingTop,
      c1Border: getComputedStyle(document.getElementById('c1')).borderTopColor,
      c2Border: getComputedStyle(document.getElementById('c2')).borderTopColor,
      t1Color: getComputedStyle(document.getElementById('t1')).color,
    })""")
    expected = {
        "c1Padding": "16px",
        "c1Border": "rgb(203, 213, 225)",
        "c2Border": "rgb(22, 163, 74)",
        "t1Color": "rgb(29, 78, 216)",
    }
    return dict(name="scss_nesting_and_parent_selector", expected=expected, actual=actual, passed=(actual == expected))


def case_scss_mixin_and_math_equivalence(page):
    # Equivalent compiled CSS of:
    # $base-gap: 8px;
    # @mixin pill($bg) { background-color: $bg; padding: $base-gap ($base-gap * 2); border-radius: 9999px; color: #fff; }
    # .badge-info { @include pill(#2563eb); } .badge-warn { @include pill(#d97706); }
    compiled_css = """.badge-info { background-color: #2563eb; padding: 8px 16px; border-radius: 9999px; color: #ffffff; display: inline-block; }
.badge-warn { background-color: #d97706; padding: 8px 16px; border-radius: 9999px; color: #ffffff; display: inline-block; }"""
    html = f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{compiled_css}</style></head>
<body>
  <span id="info" class="badge-info">Info</span>
  <span id="warn" class="badge-warn">Warn</span>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("""() => {
      const i = getComputedStyle(document.getElementById('info'));
      const w = getComputedStyle(document.getElementById('warn'));
      return {
        infoBg: i.backgroundColor,
        warnBg: w.backgroundColor,
        padY: i.paddingTop,
        padX: i.paddingLeft,
        radius: i.borderTopLeftRadius,
      };
    }""")
    expected = {
        "infoBg": "rgb(37, 99, 235)",
        "warnBg": "rgb(217, 119, 6)",
        "padY": "8px",
        "padX": "16px",
        "radius": "9999px",
    }
    return dict(name="scss_mixin_and_math_equivalence", expected=expected, actual=actual, passed=(actual == expected))


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page()
            cases = [
                case_scss_variable_compilation_to_css(page),
                case_scss_nesting_and_parent_selector(page),
                case_scss_mixin_and_math_equivalence(page),
            ]
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对 $myColor 编译后 h1 计算颜色为 rgb(255,0,0) 且不含 $ 符号,以及嵌套 .card.active 边框变绿、@mixin 胶囊徽章计算尺寸与背景色。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a3188.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:React

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3188.zip

下载课程关联工程包:React

课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

浏览器 CSS 解析器不识别 $ 变量、@mixin 等 Sass 语法;安装 npm i sass 后,开发服务器与打包工具(如 Vite/Webpack)会在构建期调用 Dart Sass 将 .scss 编译为标准 CSS 再注入页面。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习