如何在 Docusaurus 中动态加载 RTL CSS 并切换字体?

解读

国内多数团队把 Docusaurus 当成“官网+文档”一体化方案,面试时问这道题,不是考你会不会写一句 direction: rtl,而是看你是否能把“国际化、可维护、性能、CI/CD”四条线串起来。
面试官潜台词:

  1. 站点要同时服务中东客户(RTL)和国内客户(LTR),不能打包两份产物。
  2. 字体文件有版权,必须走公司 CDN,且要按语言懒加载,首屏不能多 1 KB。
  3. 项目用 GitLab CI,脚本必须让测试、产品、运维都能看懂,不能留坑。
  4. 上线后如果阿拉伯同事反馈“字形被浏览器回退成系统宋体”,你要能在 30 分钟内定位是 CSS 权重还是字体格式问题。

一句话:这道题考“动态”二字,也考“工程化落地”。

知识点

  1. Docusaurus 插件生命周期:loadContent、configureWebpack、postBuild。
  2. 客户端路由事件:onRouteUpdate 可拿到 location.pathname,配合 i18n.currentLocale 判断当前语言。
  3. Webpack 的 style-loader 与 mini-css-extract-plugin 差异:前者可 runtime 插入,后者打出的 chunk 需手动 preload。
  4. CSS 逻辑属性:margin-inline-start、padding-block-end 等,避免写两套物理属性。
  5. 字体分段加载:
    • 用 unicode-range 把阿拉伯字符区间单独拆包;
    • 用 font-display: optional 防止阻塞渲染;
    • 用 preload 仅对首屏关键路径语言生效。
  6. 公司合规:CDN 域名需备案,字体文件需走内网 S3 并加 Referer 防盗链。
  7. 测试策略:
    • 单元:Jest 快照检测编译后 CSS 是否包含 [dir=rtl] 选择器;
    • E2E:Playwright 切换语言后断言 document.documentElement.dir === 'rtl' 且 getComputedStyle(fontFamily) 含 "Noto Naskh Arabic"。

答案

给出一个可直接搬进公司仓库的“三步走”方案,不魔改 Docusaurus 源码,全部用官方插件入口完成。

第一步:插件注册
在项目根新建 plugins/docusaurus-plugin-rtl-font/index.js:

const path = require('path');
module.exports = function (context) {
  return {
    name: 'docusaurus-plugin-rtl-font',
    configureWebpack() {
      return {
        module: {
          rules: [
            {
              test: /rtl\.css$/i,
              use: [
                'style-loader',
                'css-loader',
                {
                  loader: 'postcss-loader',
                  options: {
                    postcssOptions: {
                      plugins: [
                        require('postcss-logical')(), // 自动把 float:left 转成 float:inline-start
                        require('autoprefixer')
                      ]
                    }
                  }
                }
              ]
            }
          ]
        }
      };
    },
    injectHtmlTags({siteConfig}) {
      // 仅当构建语言包含 ar 或 he 时才插入 preload
      const rtlLocales = ['ar', 'he'];
      const needsRtl = siteConfig.i18n.locales.some(l => rtlLocales.includes(l));
      if (!needsRtl) return {};
      return {
        headTags: [
          {
            tagName: 'link',
            attributes: {
              rel: 'preload',
              href: 'https://cdn.mycompany.com/fonts/NotoNaskhArabic-Regular.woff2',
              as: 'font',
              type: 'font/woff2',
              crossorigin: 'anonymous'
            }
          }
        ]
      };
    }
  };
};

第二步:客户端运行时脚本
新建 src/components/RtlProvider/index.tsx:

import React, {useEffect} from 'react';
import {useLocation} from '@docusaurus/router';
import {usePluginData} from '@docusaurus/useGlobalData';

export default function RtlProvider({children}) {
  const {pathname} = useLocation();
  const {i18n} = usePluginData('docusaurus-plugin-rtl-font');
  const isRtl = i18n.currentLocale === 'ar' || i18n.currentLocale === 'he';

  useEffect(() => {
    // 动态插入 RTL 样式
    if (isRtl) {
      import('./rtl.css');  // 被 webpack 拆成独立 chunk,仅当需要时加载
    }
    // 设置根元素方向
    document.documentElement.dir = isRtl ? 'rtl' : 'ltr';
    // 切换字体
    document.documentElement.style.setProperty(
      '--ifm-font-family-base',
      isRtl ? 'Noto Naskh Arabic, Roboto, sans-serif' : 'Roboto, sans-serif'
    );
  }, [isRtl]);

  return <>{children}</>;
}

在 docusaurus.config.js 里把组件包进 themeConfig.navbar.items 同级:

themeConfig: {
  // ...
},
customFields: {
  RtlProvider: require.resolve('./src/components/RtlProvider'),
},

并在 src/theme/Root.tsx 中统一挂载:

import RtlProvider from '@site/src/components/RtlProvider';
export default function Root({children}) {
  return <RtlProvider>{children}</RtlProvider>;
}

第三步:CI/CD 与验证
.gitlab-ci.yml 片段:

rtl-test:
  stage: test
  script:
    - npm run build -- --locale ar
    - npx playwright test
  only:
    changes:
      - "plugins/docusaurus-plugin-rtl-font/**"
      - "src/components/RtlProvider/**"

Playwright 用例:

test('arabic font loaded', async ({page}) => {
  await page.goto('/ar/docs/intro');
  await expect(page.locator('html')).toHaveAttribute('dir', 'rtl');
  const ff = await page.evaluate(() =>
    getComputedStyle(document.body).fontFamily
  );
  expect(ff).toContain('Noto Naskh Arabic');
});

上线后,阿拉伯用户首次访问 /ar/** 路径时,浏览器会:

  1. 并行下载 rtl.css chunk(gzip 后 < 3 KB);
  2. 下载 NotoNaskhArabic-Regular.woff2(92 KB,已 preload);
  3. 切换根元素 dir 与 CSS 变量,无闪屏。

运维监控:在阿里云 SLS 里对 cdn.mycompany.com/fonts/*.woff2 4xx 报警阈值设为 1%,一旦字体被 Referer 拦截立即飞书告警。

拓展思考

  1. 如果产品后续增加波斯语(fa-IR),只需把 rtlLocales 数组 push 进去,无需改构建脚本;但波斯语部分字符与阿拉伯语字形差异大,需再拆一个 fa-IR.woff2,可通过 unicode-range: U+0600-06FF, U+0750-077F 细化。
  2. 为了 SEO,阿拉伯语路由 /ar/** 要在 sitemap.xml 里加 hreflang="ar-SA",并在百度站长平台主动推送,否则国内搜索引擎会当成重复内容降权。
  3. 若公司改用 Nextra 或 VitePress,思路不变:利用虚拟模块 + 异步 import() 实现 chunk 级懒加载,但要把 Webpack 的 style-loader 换成 Vite 的 ?inline 查询参数,PostCSS 插件保持一致即可。