Files
test-repo/docs/api.md
T

177 lines
7.0 KiB
Markdown
Raw Normal View History

2017-11-07 14:39:07 +11:00
---
id: api
title: API
---
If you want to run Prettier programmatically, check this page out.
2017-11-07 14:39:07 +11:00
```js
2022-09-26 19:28:43 +08:00
import * as prettier from "prettier";
2017-11-07 14:39:07 +11:00
```
2021-03-10 02:54:50 +02:00
## `prettier.format(source, options)`
2017-11-07 14:39:07 +11:00
2021-03-10 02:54:50 +02:00
`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](options.md#parser)). Alternatively, `options.filepath` can be specified for Prettier to infer the parser from the file extension. Other [options](options.md) may be provided to override the defaults.
2017-11-07 14:39:07 +11:00
```js
await prettier.format("foo ( );", { semi: false, parser: "babel" });
2022-09-26 19:28:43 +08:00
// -> 'foo()\n'
2017-11-07 14:39:07 +11:00
```
## `prettier.check(source [, options])`
`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.
2017-11-07 14:39:07 +11:00
## `prettier.formatWithCursor(source [, options])`
2017-11-22 19:27:40 +08:00
`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.
2017-11-07 14:39:07 +11:00
The `cursorOffset` option should be provided, to specify where the cursor is. This option cannot be used with `rangeStart` and `rangeEnd`.
```js
await prettier.formatWithCursor(" 1", { cursorOffset: 2, parser: "babel" });
2017-11-07 14:39:07 +11:00
// -> { formatted: '1;\n', cursorOffset: 1 }
```
## `prettier.resolveConfig(filePath [, options])`
`resolveConfig` can be used to resolve configuration for a given source file, passing its path as the first argument. The config search will start at the file path and continue to search up the directory (you can use `process.cwd()` to start searching from the current 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:
2017-11-22 19:27:40 +08:00
2018-05-27 15:37:44 -03:00
- An options object, providing a [config file](configuration.md) was found.
- `null`, if no file was found.
2017-11-07 14:39:07 +11:00
The promise will be rejected if there was an error parsing the configuration file.
If `options.useCache` is `false`, all caching will be bypassed.
```js
const text = await fs.readFile(filePath, "utf8");
const options = await prettier.resolveConfig(filePath);
const formatted = await prettier.format(text, options);
2017-11-07 14:39:07 +11:00
```
If `options.editorconfig` is `true` and an [`.editorconfig` file](https://editorconfig.org/) 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`
2018-05-27 15:37:44 -03:00
- `indent_style`
- `indent_size`/`tab_width`
- `max_line_length`
2023-09-04 19:59:42 +08:00
## `prettier.resolveConfigFile([fileUrlOrPath])`
`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:
2018-05-27 15:37:44 -03:00
- The path of the configuration file.
- `null`, if no file was found.
The promise will be rejected if there was an error parsing the configuration file.
2023-09-04 19:59:42 +08:00
The search starts at `process.cwd()`, or at `fileUrlOrPath` if provided. Please see the [lilconfig docs](https://github.com/antonk52/lilconfig) for details on how the resolving works.
```js
const configFile = await prettier.resolveConfigFile(filePath);
// you got the path of the configuration file
```
2017-11-07 14:39:07 +11:00
## `prettier.clearConfigCache()`
2020-02-27 22:43:02 +08:00
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.
2017-11-07 14:39:07 +11:00
## `prettier.getFileInfo(filePath [, options])`
`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:
2022-09-26 19:28:43 +08:00
```ts
{
2022-09-26 19:28:43 +08:00
ignored: boolean;
inferredParser: string | null;
}
```
2019-10-17 01:53:01 +09:00
The promise will be rejected if the type of `filePath` is not `string`.
2023-04-10 10:51:46 +08:00
Setting `options.ignorePath` (`string | string[]`) and `options.withNodeModules` (`boolean`) influence the value of `ignored` (`false` by default).
If the given `filePath` is ignored, the `inferredParser` is always `null`.
Providing [plugin](plugins.md) paths in `options.plugins` (`string[]`) helps extract `inferredParser` for files that are not supported by Prettier core.
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()`
2017-11-07 14:39:07 +11:00
2022-05-06 09:27:54 +08:00
Returns a promise which resolves to an object representing the options, parsers, languages and file types Prettier supports.
2017-11-07 14:39:07 +11:00
The support information looks like this:
2022-09-26 19:28:43 +08:00
```ts
2017-11-07 14:39:07 +11:00
{
languages: Array<{
2022-06-14 14:33:25 +08:00
name: string;
parsers: string[];
group?: string;
tmScope?: string;
aceMode?: string;
codemirrorMode?: string;
codemirrorMimeType?: string;
aliases?: string[];
extensions?: string[];
filenames?: string[];
linguistLanguageId?: number;
vscodeLanguageIds?: string[];
}>;
2017-11-07 14:39:07 +11:00
}
```
<a name="custom-parser-api"></a>
2017-11-07 14:39:07 +11:00
## Custom Parser API (removed)
_Removed in v3.0.0 (superseded by the Plugin API)_
Before [plugins](plugins.md) 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.
❌ Custom parser API (removed):
2017-11-22 19:27:40 +08:00
2017-11-07 14:39:07 +11:00
```js
import { format } from "prettier";
2017-11-07 14:39:07 +11:00
format("lodash ( )", {
2018-12-27 08:05:19 -05:00
parser(text, { babel }) {
const ast = babel(text);
2017-11-07 14:39:07 +11:00
ast.program.body[0].expression.callee.name = "_";
return ast;
2020-03-21 22:07:52 +02:00
},
2017-11-07 14:39:07 +11:00
});
// -> "_();\n"
```
✔️ Plugin API:
```js
import { format } from "prettier";
2023-07-08 08:23:19 +08:00
import * as prettierPluginBabel from "prettier/plugins/babel";
const myCustomPlugin = {
parsers: {
"my-custom-parser": {
async parse(text) {
2023-07-08 08:23:19 +08:00
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"
```
> 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](https://github.com/facebook/jscodeshift) if you need codemods.
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](plugins.md#using-plugins).