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

128 lines
2.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Rust Formatter (WASM)
一个基于 WebAssembly 的 Rust 代码格式化工具,可以在浏览器和 Node.js 环境中使用。
## 特性
- 🚀 基于 WebAssembly性能优异
- 🌍 支持浏览器和 Node.js 环境
- ⚙️ 支持配置选项tab/space 缩进)
- 📦 轻量级,无需额外的 Rust 工具链
- 🔧 基于 `prettyplease``syn` 提供准确的格式化
## 安装
```bash
npm install @landaiqing/rust_fmt
```
## 使用方法
### Node.js
```javascript
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)
```javascript
import init, { format } from '@landaiqing/rust_fmt';
await init();
const rustCode = `fn main(){println!("Hello, world!");}`;
const formatted = format(rustCode);
console.log(formatted);
```
### Vite
```javascript
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 接口
```typescript
interface Config {
/**
* 当设置为 true 时,使用 tab 缩进而不是空格缩进
*
* 默认值: false
*/
use_tabs?: boolean;
}
```
## 开发
### 构建
```bash
# 安装依赖
cargo build
# 构建 WASM 包
wasm-pack build --target=web --scope=landaiqing
# 复制额外文件
cp -R ./extra/. ./pkg/
# 处理 package.json
node ./scripts/package.mjs ./pkg/package.json
```
### 测试
```bash
# 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](https://github.com/dtolnay/prettyplease) - Rust 代码格式化库
- [syn](https://github.com/dtolnay/syn) - Rust 语法解析库
- [wasm-bindgen](https://github.com/rustwasm/wasm-bindgen) - Rust 和 WebAssembly 绑定生成器