Files
rust_fmt/README.md
2025-09-20 20:44:24 +08:00

2.4 KiB
Raw Blame History

Rust Formatter (WASM)

一个基于 WebAssembly 的 Rust 代码格式化工具,可以在浏览器和 Node.js 环境中使用。

特性

  • 🚀 基于 WebAssembly性能优异
  • 🌍 支持浏览器和 Node.js 环境
  • ⚙️ 支持配置选项tab/space 缩进)
  • 📦 轻量级,无需额外的 Rust 工具链
  • 🔧 基于 prettypleasesyn 提供准确的格式化

安装

npm install @landaiqing/rust_fmt

使用方法

Node.js

import init, { format } from '@landaiqing/rust_fmt';

await init();

const rustCode = `fn main(){println!("Hello, world!");}`;

// 使用默认配置(空格缩进)
const formatted = format(rustCode);
console.log(formatted);

// 使用 tab 缩进
const formattedWithTabs = format(rustCode, { use_tabs: true });
console.log(formattedWithTabs);

浏览器 (ES Modules)

import init, { format } from '@landaiqing/rust_fmt';

await init();

const rustCode = `fn main(){println!("Hello, world!");}`;
const formatted = format(rustCode);
console.log(formatted);

Vite

import init, { format } from '@landaiqing/rust_fmt/vite';

await init();

const rustCode = `fn main(){println!("Hello, world!");}`;
const formatted = format(rustCode);
console.log(formatted);

API

format(input: string, config?: Config): string

格式化 Rust 代码字符串。

参数

  • input: 要格式化的 Rust 代码字符串
  • config (可选): 格式化配置选项

Config 接口

interface Config {
  /**
   * 当设置为 true 时,使用 tab 缩进而不是空格缩进
   * 
   * 默认值: false
   */
  use_tabs?: boolean;
}

开发

构建

# 安装依赖
cargo build

# 构建 WASM 包
wasm-pack build --target=web --scope=landaiqing

# 复制额外文件
cp -R ./extra/. ./pkg/

# 处理 package.json
node ./scripts/package.mjs ./pkg/package.json

测试

# Node.js 测试
node test_node/test-node.mjs

# Deno 测试
deno test test_deno/deno.test.ts --allow-read

# Bun 测试
bun test test_bun/bun.spec.ts

许可证

MIT

致谢

本项目基于以下优秀的开源项目: