如何为 Rust 插件编写 TypeScript 声明?

解读

PostCSS 的插件体系允许用任何语言实现,只要最终暴露一个 JS 可调用的接口。Rust 通过 napi-rs 或 wasm-bindgen 编译成 Node 可加载的二进制(.node 或 .wasm),但 TypeScript 无法直接识别 Rust 的结构体与枚举,必须手写或自动生成 .d.ts 文件。面试官问“如何写声明”,核心考察三点:

  1. 是否理解 PostCSS 插件的 JS 签名——函数或对象格式、接收 Root/Result、返回 Promise 或 void;
  2. 是否熟悉 napi-rs 的 TypeScript 导出机制;
  3. 能否保证声明与 Rust 实际 ABI 完全对齐,避免运行时崩溃或类型漂移。
    国内大厂(阿里、字节、腾讯)在 Node 基建中大量使用 Rust 加速,面试时若能把“编译-声明-发布”整条链路讲透,可立即拉开差距。

知识点

  1. PostCSS 插件最小形状

    type Plugin = (root: Root, result: Result) => Promise<void> | void;
    

    或

    interface PluginCreator {
      (opts?: any): { postcssPlugin: string; Once?(root: Root, result: Result): void };
    }
    
  2. napi-rs 的 type-def 特性
    在 Cargo.toml 开启 "type-def" feature,编译时自动生成 index.d.ts;也可手动调用 napi build --platform --dts。

  3. wasm-bindgen 的 typescript_target
    通过 wasm-bindgen --typescript 生成 .d.ts,但默认是浏览器风格,需要二次加工抹平 Node 差异(Buffer、stream 等)。

  4. 结构体映射规则
    Rust 的 #[napi(object)] 会生成 TS interface;#[napi(string_enum)] 会生成字符串联合类型;Result<T, E> 必须转成 TS 的 T | never 并在 napi 侧 map_err(|e| Error::new(Status::GenericFailure, e.to_string()))。

  5. 版本锁定与 CI
    国内镜像源(淘宝源、字节 cnpm)常缓存旧版,需在 .npmrc 写 registry=https://registry.npmmirror.com 并在 GitHub Actions 里 cargo install napi-cli --locked,保证开发机、CI、生产三方编译产物哈希一致。

  6. 类型漂移检查
    把生成的 index.d.ts 加入 tsc --noEmit 的 files 列表,并在 husky 的 pre-commit 钩子中跑 cargo test && napi build --dts && tsc,防止 Rust 侧改字段而 TS 侧未同步。

答案

步骤一:在 Rust 侧用 napi-rs 暴露插件入口

use napi::bindgen_prelude::*;
use napi_derive::module_exports;

#[module_exports]
fn init(mut exports: JsObject) -> Result<()> {
    exports.create_named_method("postcssPluginRust", js_plugin)?;
    Ok(())
}

#[napi]
fn js_plugin(root_json: String, result_json: String) -> Result<String> {
    // 1. 解析 JSON 到 Rust AST
    let root: PostCssRoot = serde_json::from_str(&root_json)?;
    // 2. 执行 Rust 逻辑
    transform(&mut root);
    // 3. 序列化回 JSON 给 PostCSS
    Ok(serde_json::to_string(&root)?)
}

步骤二:napi 自动生成 index.d.ts

napi build --platform --dts

生成的文件大致如下:

export interface PostCssRoot { type: 'root'; nodes: Array<PostCssRule>; }
export function postcssPluginRust(rootJson: string, resultJson: string): string;

步骤三:手工封装成 PostCSS 认可的插件形状

// lib/index.d.ts
import { PostCssRoot } from './native';
import { Root, Result } from 'postcss';

declare function creator(opts?: {}): {
  postcssPlugin: 'postcss-rust-optimizer';
  Once(root: Root, result: Result): Promise<void>;
};

export = creator;
// lib/index.js
const native = require('../index.node');
const creator = () => ({
  postcssPlugin: 'postcss-rust-optimizer',
  async Once(root, result) {
    const rootJson = JSON.stringify(root.toJSON());
    const resultJson = JSON.stringify({ messages: result.messages });
    const outJson = native.postcssPluginRust(rootJson, resultJson);
    const newRootObj = JSON.parse(outJson);
    root.removeAll();          // 清空原树
    root.append(newRootObj);   // 回填新树
  }
});
module.exports = creator;

步骤四:在 package.json 中指明 types 字段

"main": "lib/index.js",
"types": "lib/index.d.ts",
"files": ["lib", "index.node"]

步骤五:本地验证

npm link
cd ../my-vite-project
npm link postcss-rust-optimizer
echo "require('postcss-rust-optimizer')().postcssPlugin" | node -p
# 输出 'postcss-rust-optimizer' 即成功

拓展思考

  1. 性能与兼容性权衡
    若插件需跑在 ARM 云函数(国内阿里云 FC、腾讯云 SCF),必须交叉编译 aarch64-unknown-linux-musl,并在发布前用 ldd index.node 检查无 glibc 依赖,否则线上会报 version GLIBC_2.29 not found。

  2. 类型安全再升级
    把 PostCSS AST 的完整 TS 定义搬进 Rust,用 serde 做双向映射,可彻底抛弃 JSON 字符串中转,改用 napi 的 JsObject 直接读写,性能提升 20% 以上,但开发成本翻倍,适合高频调用(如字节跳动的百万级文件构建集群)。

  3. 与 SWC 插件并存
    国内越来越多项目把 SWC 做 transform、PostCSS 做 prefix/minify。若 Rust 插件同时提供 SWC 和 PostCSS 两个入口,可在同一包内导出 swcPlugin 和 postcssPlugin,用 exports 字段做条件导出,实现“一次编译、两处使用”,降低维护成本。

  4. 声明文件自动化治理
    在 monorepo 中,可把 napi 生成的 .d.ts 作为 *.rs.d.ts 提交,再用 tsc --build --force 做增量检查,避免多人协作时“Rust 改一行、TS 报一百错”的惨案,这套方案已在蚂蚁集团的 ant-design-crust 仓库落地。