API
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
如需以编程方式运行 Prettier,请查阅本页内容。
import * as prettier from "prettier";
我们的公共 API 均为异步接口,如因特殊原因需使用同步版本,可尝试 @prettier/sync。
prettier.format(source, options)
format 用于通过 Prettier 格式化文本。必须根据待格式化语言设置 options.parser(参见可用解析器列表)。也可指定 options.filepath 让 Prettier 根据文件扩展名推断解析器。可通过其他选项覆盖默认设置。
await prettier.format("foo ( );", { semi: false, parser: "babel" });
// -> 'foo()\n'
prettier.check(source [, options])
check 用于检查文件是否已按指定选项通过 Prettier 格式化,返回 Promise<boolean>。功能类似于 CLI 中的 --check 或 --list-different 参数,适用于 CI 场景。
prettier.formatWithCursor(source [, options])
formatWithCursor 在格式化代码的同时,会将光标位置从未格式化代码映射到格式化后代码。这对编辑器集成非常有用,可防止代码格式化时光标偏移。
需提供 cursorOffset 选项以指定光标位置。
await prettier.formatWithCursor(" 1", { cursorOffset: 2, parser: "babel" });
// -> { formatted: '1;\n', cursorOffset: 1 }
prettier.resolveConfig(fileUrlOrPath [, options])
resolveConfig 用于解析指定源文件的配置,其路径或 URL 作为首个参数传入。配置搜索从文件所在目录开始并向父级目录递归。若不想搜索,可直接将配置文件路径作为 options.config 传入。函数返回的 Promise 可能解析为:
-
选项对象(当找到配置文件时)
-
null(未找到文件时)
若配置文件解析出错,Promise 将被拒绝。
若 options.useCache 为 false,将绕过所有缓存。
const text = await fs.readFile(filePath, "utf8");
const options = await prettier.resolveConfig(filePath);
const formatted = await prettier.format(text, {
...options,
filepath: filePath,
});
当 options.editorconfig 为 true 且项目中存在 .editorconfig 文件时,Prettier 会解析该文件并将其属性转换为对应配置。此配置将被 .prettierrc 等文件覆盖。当前支持以下 EditorConfig 属性:
-
end_of_line -
indent_style(缩进风格) -
indent_size/tab_width(缩进大小/制表符宽度) -
max_line_length(最大行宽)
prettier.resolveConfigFile([fileUrlOrPath])
resolveConfigFile 用于查找解析配置时将使用的 Prettier 配置文件路径(即调用 resolveConfig 时)。函数返回的 Promise 可能解析为:
-
配置文件路径
-
null(未找到文件时)
若配置文件解析出错,Promise 将被拒绝。
搜索从 process.cwd() 开始,若提供 fileUrlOrPath 则从其所在目录开始。
const configFile = await prettier.resolveConfigFile(filePath);
// you got the path of the configuration file
prettier.clearConfigCache()
Prettier 加载配置文件和插件时会缓存文件系统结构以提升性能。此函数用于清除缓存,通常仅在编辑器集成感知到文件系统自上次格式化后发生变更时使用。
prettier.getFileInfo(fileUrlOrPath [, options])
getFileInfo 方法可供编辑器扩展使用,用于判断特定文件是否需要格式化。该方法返回一个 Promise,解析为包含以下属性的对象:
{
ignored: boolean;
inferredParser: string | null;
}
如果 fileUrlOrPath 类型不是 string 或 URL,Promise 将被拒绝。
设置 options.ignorePath (string | URL | (string | URL)[]) 和 options.withNodeModules (boolean) 会影响 ignored 的值(默认为 false)。
如果给定的 fileUrlOrPath 被忽略,inferredParser 始终为 null。
在 options.plugins ((string | URL | Plugin)[]) 中提供插件路径,有助于为非 Prettier 核心支持的文件提取 inferredParser。
当设置 options.resolveConfig (boolean, 默认 true) 为 false 时,Prettier 将不会搜索配置文件。这在仅需检查文件是否被忽略时非常有用。
prettier.getSupportInfo()
返回一个 Promise,解析为表示 Prettier 支持的选项、解析器、语言和文件类型的对象。
支持信息结构如下:
{
languages: Array<{
name: string;
parsers: string[];
group?: string;
tmScope?: string;
aceMode?: string;
codemirrorMode?: string;
codemirrorMimeType?: string;
aliases?: string[];
extensions?: string[];
filenames?: string[];
linguistLanguageId?: number;
vscodeLanguageIds?: string[];
isSupported?(options: { filepath: string }): boolean;
}>;
}
Prettier 无法保证 filepath 在磁盘上实际存在。
通过 API(如 prettier.format())调用时,也无法保证该路径有效。
自定义解析器 API(已移除)
v3.0.0 版本移除(由插件 API 取代)
在插件功能出现之前,Prettier 曾提供功能类似但更受限的自定义解析器特性。由于该功能仅是插件 API 的子集,已在 v3.0.0 版本移除。如需迁移方案,请参考以下示例:
❌ 已移除的自定义解析器 API:
import { format } from "prettier";
format("lodash ( )", {
parser(text, { babel }) {
const ast = babel(text);
ast.program.body[0].expression.callee.name = "_";
return ast;
},
});
// -> "_();\n"
✔️ 插件 API:
import { format } from "prettier";
import * as prettierPluginBabel from "prettier/plugins/babel";
const myCustomPlugin = {
parsers: {
"my-custom-parser": {
async parse(text) {
const ast = await prettierPluginBabel.parsers.babel.parse(text);
ast.program.body[0].expression.callee.name = "_";
return ast;
},
astFormat: "estree",
},
},
};
await format("lodash ( )", {
parser: "my-custom-parser",
plugins: [myCustomPlugin],
});
// -> "_();\n"
总体上,不推荐通过这种方式进行代码重构。Prettier 依赖 AST 节点的位置信息实现空行保留和注释关联等功能。修改解析后的 AST 会导致位置信息失准,可能引发不可预知的结果。如需代码重构工具,请考虑使用 jscodeshift。
作为已移除的自定义解析器 API 的一部分,原先可通过 --parser 选项传递导出 parse 函数的模块路径。现在请改用 --plugin CLI 选项或 plugins API 选项来加载插件。