API
如果你想以编程方式运行 Prettier,请查看此页面。
¥If you want to run Prettier programmatically, check this page out.
import * as prettier from "prettier";
我们的公共 API 都是异步的,如果你因为某种原因必须使用同步版本,你可以尝试 @prettier/sync
。
¥Our public APIs are all asynchronous, if you must use synchronous version for some reason, you can try @prettier/sync
.
prettier.format(source, options)
format
用于使用 Prettier 格式化文本。options.parser
必须根据你正在格式化的语言进行设置(请参阅 可用解析器列表)。或者,可以为 Prettier 指定 options.filepath
,以从文件扩展名推断解析器。可以提供其他 options 来覆盖默认值。
¥format
is used to format text using Prettier. options.parser
must be set according to the language you are formatting (see the list of available parsers). Alternatively, options.filepath
can be specified for Prettier to infer the parser from the file extension. Other options may be provided to override the defaults.
await prettier.format("foo ( );", { semi: false, parser: "babel" });
// -> 'foo()\n'
prettier.check(source [, options])
check
检查文件是否已使用给定这些选项的 Prettier 格式化并返回 Promise<boolean>
。这类似于 CLI 中的 --check
或 --list-different
参数,对于在 CI 场景中运行 Prettier 很有用。
¥check
checks to see if the file has been formatted with Prettier given those options and returns a Promise<boolean>
. This is similar to the --check
or --list-different
parameter in the CLI and is useful for running Prettier in CI scenarios.
prettier.formatWithCursor(source [, options])
formatWithCursor
既格式化代码,又将光标位置从未格式化代码转换为格式化代码。这对于编辑器集成很有用,可以防止在格式化代码时光标移动。
¥formatWithCursor
both formats the code, and translates a cursor position from unformatted code to formatted code. This is useful for editor integrations, to prevent the cursor from moving when code is formatted.
应提供 cursorOffset
选项,以指定光标所在的位置。
¥The cursorOffset
option should be provided, to specify where the cursor is.
await prettier.formatWithCursor(" 1", { cursorOffset: 2, parser: "babel" });
// -> { formatted: '1;\n', cursorOffset: 1 }
prettier.resolveConfig(fileUrlOrPath [, options])
resolveConfig
可用于解析给定源文件的配置,将其路径或 url 作为第一个参数传递。配置搜索将从文件位置的目录开始,并继续向上搜索该目录。或者如果你不想搜索它,你可以直接将配置文件的路径作为 options.config
传递。返回一个 promise,它将解析为:
¥resolveConfig
can be used to resolve configuration for a given source file, passing its path or url as the first argument. The config search will start at the directory of the file location and continue to search up the directory. Or you can pass directly the path of the config file as options.config
if you don’t wish to search for it. A promise is returned which will resolve to:
找到一个提供 配置文件 的选项对象。
¥An options object, providing a config file was found.
null
,如果没有找到文件。¥
null
, if no file was found.
如果解析配置文件时出错,promise 将被拒绝。
¥The promise will be rejected if there was an error parsing the configuration file.
如果 options.useCache
是 false
,所有的缓存都会被绕过。
¥If options.useCache
is false
, all caching will be bypassed.
const text = await fs.readFile(filePath, "utf8");
const options = await prettier.resolveConfig(filePath);
const formatted = await prettier.format(text, options);
如果 options.editorconfig
是 true
,而你的项目中有一个 .editorconfig
档,Prettier 会对其进行解析,并将其属性转换为对应的 Prettier 配置。该配置会被 .prettierrc
等覆盖。目前支持以下 EditorConfig 属性:
¥If options.editorconfig
is true
and an .editorconfig
file is in your project, Prettier will parse it and convert its properties to the corresponding Prettier configuration. This configuration will be overridden by .prettierrc
, etc. Currently, the following EditorConfig properties are supported:
end_of_line
indent_style
indent_size
/tab_width
max_line_length
prettier.resolveConfigFile([fileUrlOrPath])
resolveConfigFile
可用于查找解析配置时(即调用 resolveConfig
时)将使用的 Prettier 配置文件的路径。返回一个 promise,它将解析为:
¥resolveConfigFile
can be used to find the path of the Prettier configuration file that will be used when resolving the config (i.e. when calling resolveConfig
). A promise is returned which will resolve to:
配置文件的路径。
¥The path of the configuration file.
null
,如果没有找到文件。¥
null
, if no file was found.
如果解析配置文件时出错,promise 将被拒绝。
¥The promise will be rejected if there was an error parsing the configuration file.
搜索从 process.cwd()
开始,或者从 fileUrlOrPath
的目录(如果提供)开始。
¥The search starts at process.cwd()
, or at the directory of fileUrlOrPath
if provided.
const configFile = await prettier.resolveConfigFile(filePath);
// you got the path of the configuration file
prettier.clearConfigCache()
当 Prettier 加载配置文件和插件时,会缓存文件系统结构以提高性能。此函数将清除缓存。通常,只有知道自上次格式发生以来文件系统已更改的编辑器集成才需要这样做。
¥When Prettier loads configuration files and plugins, the file system structure is cached for performance. This function will clear the cache. Generally this is only needed for editor integrations that know that the file system has changed since the last format took place.
prettier.getFileInfo(fileUrlOrPath [, options])
编辑器扩展可以使用 getFileInfo
来决定是否需要格式化特定文件。此方法返回一个 promise,该 promise 解析为具有以下属性的对象:
¥getFileInfo
can be used by editor extensions to decide if a particular file needs to be formatted. This method returns a promise, which resolves to an object with the following properties:
{
ignored: boolean;
inferredParser: string | null;
}
如果 fileUrlOrPath
的类型不是 string
或 URL
,则 promise 将被拒绝。
¥The promise will be rejected if the type of fileUrlOrPath
is not string
or URL
.
设置 options.ignorePath
(string | URL | (string | URL)[]
) 和 options.withNodeModules
(boolean
) 会影响 ignored
的值(默认为 false
)。
¥Setting options.ignorePath
(string | URL | (string | URL)[]
) and options.withNodeModules
(boolean
) influence the value of ignored
(false
by default).
如果忽略给定的 fileUrlOrPath
,则 inferredParser
始终为 null
。
¥If the given fileUrlOrPath
is ignored, the inferredParser
is always null
.
在 options.plugins
(string[]
) 中提供 plugin 路径有助于为 Prettier 核心不支持的文件提取 inferredParser
。
¥Providing plugin paths in options.plugins
(string[]
) helps extract inferredParser
for files that are not supported by Prettier core.
当设置 options.resolveConfig
(boolean
,默认 true
)为 false
时,Prettier 将不会搜索配置文件。如果此函数仅用于检查文件是否被忽略,则这可能很有用。
¥When setting options.resolveConfig
(boolean
, default true
) to false
, Prettier will not search for configuration file. This can be useful if this function is only used to check if file is ignored.
prettier.getSupportInfo()
返回一个 promise,该 promise 解析为表示 Prettier 支持的选项、解析器、语言和文件类型的对象。
¥Returns a promise which resolves to an object representing the options, parsers, languages and file types Prettier supports.
支持信息如下所示:
¥The support information looks like this:
{
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[];
}>;
}
自定义解析器 API(已删除)
¥Custom Parser API (removed)
在 v3.0.0 中删除(由插件 API 取代)
¥Removed in v3.0.0 (superseded by the Plugin API)
在 插件 出现之前,Prettier 有一个类似但更有限的功能,称为自定义解析器。它在 v3.0.0 中被删除,因为它的功能是插件 API 功能的子集。如果你使用过它,请查看下面的示例以了解如何迁移。
¥Before plugins were a thing, Prettier had a similar but more limited feature called custom parsers. It’s been removed in v3.0.0 as its functionality was a subset of what the Plugin API did. If you used it, please check the example below on how to migrate.
❌ 自定义解析器 API(已删除):
¥❌ Custom parser API (removed):
import { format } from "prettier";
format("lodash ( )", {
parser(text, { babel }) {
const ast = babel(text);
ast.program.body[0].expression.callee.name = "_";
return ast;
},
});
// -> "_();\n"
✔️ 插件接口:
¥✔️ Plugin 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"
注意:总的来说,不推荐以这种方式进行 codemod。Prettier 使用 AST 节点的位置数据来做很多事情,比如保留空行和附加注释。当解析后修改 AST 时,位置数据经常会不同步,这可能会导致不可预测的结果。如果你需要代码模块,请考虑使用 jscodeshift。
¥Note: Overall, doing codemods this way isn’t recommended. Prettier uses the location data of AST nodes for many things like preserving blank lines and attaching comments. When the AST is modified after the parsing, the location data often gets out of sync, which may lead to unpredictable results. Consider using jscodeshift if you need codemods.
作为已删除的自定义解析器 API 的一部分,以前可以通过 --parser
选项将路径传递给导出 parse
函数的模块。使用 --plugin
CLI 选项或 plugins
API 选项代替 加载插件。
¥As part of the removed Custom parser API, it was previously possible to pass a path to a module exporting a parse
function via the --parser
option. Use the --plugin
CLI option or the plugins
API option instead to load plugins.