xDocxDoc
AI
前端
后端
iOS
Android
Flutter
AI
前端
后端
iOS
Android
Flutter
  • 关于

    • Prettier
    • 构建并强制执行
    • Prettier vs. Linters
    • 选项设计原理
    • 设计理念
  • 使用

    • 安装指南
    • 忽略代码
    • precommit
    • 插件
    • CLI
    • API
    • Browser
    • CI
  • 配置 Prettier

    • options
    • Configuration File
    • 共享配置
  • Editors

    • 编辑器集成
    • WebStorm 设置
    • Vim 配置指南
    • 监视文件变更
  • Misc

    • 技术实现细节
    • 生态
    • 企业解决方案

API

如需通过编程方式运行 Prettier,请参考本页文档。

// 基础导入方式
import * as prettier from "prettier";

// 同步API替代方案(仅特殊场景需要)
import * as prettierSync from "@prettier/sync"; // 来自 https://github.com/prettier/prettier-synchronized

⚠️ 异步优先原则:
所有公开API均为异步设计,同步版本请谨慎使用 @prettier/sync

prettier.format(source, options)

核心格式化方法,接收源码文本和配置选项,返回格式化后的代码。

参数类型必填说明
sourcestring是待格式化的源代码字符串
optionsobject是配置对象(详见options.md)

关键配置项:

  • parser:必须指定,根据语言选择解析器(参见options.md#parser)
  • filepath:可通过文件路径自动推断解析器(替代parser配置)
  • 其他选项覆盖默认规则
// 格式化示例(禁用分号+指定Babel解析器)
const formatted = await prettier.format("foo ( );", { 
  semi: false, 
  parser: "babel" 
});
// 输出:'foo()\n'

prettier.check(source [, options])

校验源代码是否已符合Prettier格式化标准,返回Promise<boolean>。此方法对应于CLI的--check或--list-different参数,特别适用于CI/CD场景。

// CI流程中的校验示例
const needsFormatting = await prettier.check(unformattedCode, {
  parser: "typescript",
  tabWidth: 2
});
if (needsFormatting) throw new Error("代码需要重新格式化!");

prettier.formatWithCursor(source [, options])

编辑器集成专用方法:在格式化代码的同时映射光标位置,防止格式化后光标意外偏移。

特殊选项类型必填说明
cursorOffsetnumber是原始代码中的光标偏移位置
// 格式化并转换光标位置
const result = await prettier.formatWithCursor(" 1", { 
  cursorOffset: 2,   // 原光标在空格后数字"1"的位置
  parser: "babel" 
});
// 返回:{ formatted: '1;\n', cursorOffset: 1 } → 新光标在"1"后

prettier.resolveConfig(fileUrlOrPath [, options])

解析文件路径对应的配置,返回Promise<配置对象|null>。配置查找逻辑:

  1. 从文件所在目录开始搜索
  2. 逐级向上查找配置文件
  3. 找到有效配置返回对象,未找到返回null
高级选项类型默认值说明
configstring-直接指定配置文件路径(跳过搜索)
useCachebooleantrue禁用配置缓存
editorconfigbooleantrue是否读取.editorconfig文件
// 标准工作流示例
const filePath = "./src/index.js";
const code = await fs.readFile(filePath, "utf8");

// 解析该文件的配置
const options = await prettier.resolveConfig(filePath);

// 应用配置格式化
const formatted = await prettier.format(code, {
  ...options,
  filepath: filePath // 确保解析器自动推断
});

prettier.resolveConfigFile([fileUrlOrPath])

定位Prettier配置文件路径,返回Promise<文件路径|null>。搜索逻辑:

  1. 默认从process.cwd()开始
  2. 指定fileUrlOrPath时从其所在目录开始
// 获取配置文件路径
const configPath = await prettier.resolveConfigFile("./src/app.js");
console.log(`使用的配置文件: ${configPath || '默认配置'}`);

prettier.clearConfigCache()

性能优化方法:清除配置和插件缓存。适用于编辑器扩展场景,当检测到文件系统变更后调用。

// 文件监视回调示例
watcher.on("configChanged", () => {
  prettier.clearConfigCache();
});

prettier.getFileInfo(fileUrlOrPath [, options])

编辑器扩展专用:检测文件是否需要格式化,返回包含以下属性的对象:

{
  ignored: boolean;        // 文件是否被忽略
  inferredParser: string | null;  // 推断的解析器名称
}
选项类型默认值说明
ignorePath`stringURLArray`
withNodeModulesbooleanfalse是否检查node_modules内文件
pluginsArray[]插件列表(扩展解析器支持)
resolveConfigbooleantrue是否解析配置文件影响忽略判断
// 编辑器保存时检查示例
const fileInfo = await prettier.getFileInfo(filePath);
if (!fileInfo.ignored && fileInfo.inferredParser) {
  await formatEditorContent();
}

prettier.getSupportInfo()

获取Prettier支持的所有选项、解析器、语言和文件类型信息,返回数据结构:

{
  languages: Array<{
    name: string;           // 语言名称
    parsers: string[];      // 对应的解析器
    extensions?: string[];  // 关联文件扩展名
    filenames?: string[];   // 关联文件名
    /* 其他编辑器集成元数据 */
  }>;
}

路径验证说明:
Prettier 不会验证filepath参数的磁盘存在性或格式有效性

// 获取所有支持语言
const supportInfo = await prettier.getSupportInfo();
console.log("支持的Markdown扩展:", supportInfo.languages
  .find(lang => lang.name === "Markdown").extensions);

自定义解析器API(已弃用)

已在v3.0.0移除(由插件API取代)

迁移指南

❌ 旧版自定义解析器(v2及之前):

format("lodash ( )", {
  parser(text, { babel }) {
    const ast = babel(text);
    ast.program.body[0].expression.callee.name = "_";
    return ast; // 直接修改AST
  },
});

✔️ 新版插件方案:

// 自定义插件实现
const myPlugin = {
  parsers: {
    "my-parser": {
      async parse(text) {
        // 复用Babel解析器
        const ast = await import("prettier/plugins/babel")
          .then(mod => mod.parsers.babel.parse(text));
        // AST转换
        ast.program.body[0].expression.callee.name = "_";
        return ast;
      },
      astFormat: "estree" // 指定AST格式
    }
  }
};

// 使用插件
await format("lodash ( )", {
  parser: "my-parser",
  plugins: [myPlugin],
});

⚠️ AST操作风险提示:
直接修改AST可能导致定位信息失效(影响空行/注释保留),建议使用专业工具(如https://github.com/facebook/jscodeshift)进行代码转换。


API 使用总结

核心方法应用场景关键特性
format()基础格式化支持解析器自动推断
check()CI/CD流程检查替代prettier --check
formatWithCursor()编辑器实时格式化光标位置智能映射
resolveConfig()配置驱动格式化支持.editorconfig集成
getFileInfo()编辑器扩展忽略文件检测+解析器推断
工程方法
resolveConfigFile()配置调试定位生效配置文件
clearConfigCache()性能优化动态配置更新场景必备
高级能力
插件体系替代旧版自定义解析器通过plugins参数加载
同步API方案特殊同步场景使用@prettier/sync独立包

架构设计要点:

  1. 异步优先:所有API基于Promise设计,保障I/O密集型操作性能
  2. 配置分层:支持文件路径级精确配置,继承规则清晰
  3. 扩展性:通过插件机制取代历史遗留API
  4. 编辑器友好:提供光标映射、文件状态检测等专业接口
  5. 生态兼容:原生支持EditorConfig配置转换

最佳实践建议:生产环境优先采用异步API组合resolveConfig()+format(),编辑器集成场景使用formatWithCursor()+getFileInfo()组合方案。

最后更新: 2025/8/26 10:07
Prev
CLI
Next
Browser