748366580290354fb02342b35644870ec7a2b846
Rust Formatter (WASM)
一个基于 WebAssembly 的 Rust 代码格式化工具,可以在浏览器和 Node.js 环境中使用。
特性
- 🚀 基于 WebAssembly,性能优异
- 🌍 支持浏览器和 Node.js 环境
- ⚙️ 支持配置选项(tab/space 缩进)
- 📦 轻量级,无需额外的 Rust 工具链
- 🔧 基于
prettyplease和syn提供准确的格式化
安装
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
致谢
本项目基于以下优秀的开源项目:
- prettyplease - Rust 代码格式化库
- syn - Rust 语法解析库
- wasm-bindgen - Rust 和 WebAssembly 绑定生成器
Languages
JavaScript
42.8%
Rust
30.7%
TypeScript
24.4%
Shell
2.1%