IDE 工具函数

IDE 工具函数

概述

utils.ts 提供了 IDE 组件使用的工具函数,主要用于对象到 YAML 格式的转换。

文件路径

src/components/ide/utils.ts

函数

toYaml

将 JavaScript 对象转换为 YAML 格式的字符串。

export function toYaml(obj: unknown, indent = 0): string

参数

参数类型默认值说明
objunknown-要转换的对象
indentnumber0缩进级别

返回值

string - YAML 格式的字符串

支持类型

  • null / undefined"null"
  • string → 原样输出或多行文本(含特殊字符时加引号)
  • number / boolean → 字符串形式
  • Array → YAML 数组格式
  • Object → YAML 对象格式

使用示例

import { toYaml } from "./utils";

// 简单对象
const obj = {
  name: "example",
  count: 42,
  active: true
};
console.log(toYaml(obj));
// 输出:
// name: example
// count: 42
// active: true

// 嵌套对象
const nested = {
  person: {
    name: "John",
    age: 30
  },
  hobbies: ["reading", "coding"]
};
console.log(toYaml(nested));
// 输出:
// person:
//   name: John
//   age: 30
// hobbies:
//   - reading
//   - coding

// 多行字符串
const multiline = {
  description: "Line 1\nLine 2\nLine 3"
};
console.log(toYaml(multiline));
// 输出:
// description: |
//   Line 1
//   Line 2
//   Line 3

特性

  1. 递归处理: 支持任意深度的嵌套对象
  2. 缩进管理: 自动处理正确的 YAML 缩进
  3. 特殊字符处理: 包含 :# 的字符串会自动加引号
  4. 多行支持: 含换行符的字符串使用 | 语法
  5. 空值处理: nullundefined 统一输出为 "null"

注意事项

  1. 这是一个简化版的 YAML 序列化器,不支持所有 YAML 特性
  2. 循环引用会导致栈溢出
  3. 仅用于 IDE 内部的简单数据展示
  4. 对于复杂的 YAML 需求,建议使用专业库如 js-yaml
← 返回目录