prettier/docs/api.md

157 lines
6.0 KiB
Markdown
Raw Permalink Normal View History

---
id: api
title: API
---
```js
const prettier = require("prettier");
```
## `prettier.format(source [, options])`
`format` is used to format text using Prettier. [Options](options.md) may be provided to override the defaults.
```js
2018-12-27 16:05:19 +03:00
prettier.format("foo ( );", { semi: false, parser: "babel" });
// -> "foo()"
```
## `prettier.check(source [, options])`
2018-12-25 11:01:02 +03:00
`check` checks to see if the file has been formatted with Prettier given those options and returns a `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` 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.
The `cursorOffset` option should be provided, to specify where the cursor is. This option cannot be used with `rangeStart` and `rangeEnd`.
```js
2018-12-27 16:05:19 +03:00
prettier.formatWithCursor(" 1", { cursorOffset: 2, parser: "babel" });
// -> { 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:
2018-05-27 21:37:44 +03:00
- An options object, providing a [config file](configuration.md) was found.
- `null`, if no file was found.
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 = fs.readFileSync(filePath, "utf8");
prettier.resolveConfig(filePath).then(options => {
const formatted = prettier.format(text, options);
});
```
Re-add EditorConfig support (undo #3213) (#3255) * Revert "Revert "Respect EditorConfig settings" (#3213)" This reverts commit d2241fc0d52d807701d9a5ac580bc01010e7a93b. * Comment out EditorConfig docs See https://github.com/prettier/prettier/pull/3213#issuecomment-343009769 * editorconfig: Support `indent_size = 0` See https://github.com/prettier/prettier/pull/2760#discussion_r137447715 and https://github.com/josephfrazier/editorconfig-to-prettier/commit/c38b84c42a2e022067c104c494298a8c9533e7a7 * Revert "Comment out EditorConfig docs" This reverts commit ddfa529c55cac4853a1e76e00c8b5e3ef158c01f. * Mark EditorConfig functionality as v1.9.0+ See https://github.com/prettier/prettier/pull/3255#discussion_r150432508 * editorconfig: Upgrade editorconfig-to-prettier to 0.0.4 * editorconfig: Only enable for CLI, by default https://github.com/prettier/prettier/pull/3255#issuecomment-348420546 * editorconfig: Add tests confirming that editorconfig is ignored by default in the API https://github.com/prettier/prettier/pull/3255#issuecomment-348420546 * editorconfig: Add/fix CLI option parsing * editorconfig: Move docs from configuration.md to options.md * editorconfig: Add `oppositeDescription` to show docs for `--no-editorconfig` Addresses https://github.com/prettier/prettier/pull/3255#discussion_r154542792 * editorconfig: Update test snapshots * editorconfig: Remove unnecessary options parsing code Addresses https://github.com/prettier/prettier/pull/3255#discussion_r154544560 * editorconfig: Move docs from options.md to api.md and cli.md Addresses https://github.com/prettier/prettier/pull/3255#discussion_r154545979 * resolveConfig: return null if both .prettierrc and .editorconfig are missing Addresses https://github.com/prettier/prettier/pull/3255#discussion_r154574613 * Don't add now-failing tests The way these tests work, both `tests_integration/cli/config/.prettierrc` and `.prettierrc` apply to `tests_integration/cli/config/editorconfig/file.shouldnotexist`, so the test wouldn't work even on master. Here's a way to confirm that: ```js const path = require('path') const assert = require('assert') const prettier = require('./') const file = './tests_integration/cli/config/editorconfig/file.shouldnotexist' console.log(prettier.resolveConfig.sync(file)) assert(prettier.resolveConfig.sync(file) === null) ```
2017-12-05 01:28:27 +03:00
If `options.editorconfig` is `true` and an [`.editorconfig` file](http://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 21:37:44 +03:00
- `indent_style`
- `indent_size`/`tab_width`
- `max_line_length`
Re-add EditorConfig support (undo #3213) (#3255) * Revert "Revert "Respect EditorConfig settings" (#3213)" This reverts commit d2241fc0d52d807701d9a5ac580bc01010e7a93b. * Comment out EditorConfig docs See https://github.com/prettier/prettier/pull/3213#issuecomment-343009769 * editorconfig: Support `indent_size = 0` See https://github.com/prettier/prettier/pull/2760#discussion_r137447715 and https://github.com/josephfrazier/editorconfig-to-prettier/commit/c38b84c42a2e022067c104c494298a8c9533e7a7 * Revert "Comment out EditorConfig docs" This reverts commit ddfa529c55cac4853a1e76e00c8b5e3ef158c01f. * Mark EditorConfig functionality as v1.9.0+ See https://github.com/prettier/prettier/pull/3255#discussion_r150432508 * editorconfig: Upgrade editorconfig-to-prettier to 0.0.4 * editorconfig: Only enable for CLI, by default https://github.com/prettier/prettier/pull/3255#issuecomment-348420546 * editorconfig: Add tests confirming that editorconfig is ignored by default in the API https://github.com/prettier/prettier/pull/3255#issuecomment-348420546 * editorconfig: Add/fix CLI option parsing * editorconfig: Move docs from configuration.md to options.md * editorconfig: Add `oppositeDescription` to show docs for `--no-editorconfig` Addresses https://github.com/prettier/prettier/pull/3255#discussion_r154542792 * editorconfig: Update test snapshots * editorconfig: Remove unnecessary options parsing code Addresses https://github.com/prettier/prettier/pull/3255#discussion_r154544560 * editorconfig: Move docs from options.md to api.md and cli.md Addresses https://github.com/prettier/prettier/pull/3255#discussion_r154545979 * resolveConfig: return null if both .prettierrc and .editorconfig are missing Addresses https://github.com/prettier/prettier/pull/3255#discussion_r154574613 * Don't add now-failing tests The way these tests work, both `tests_integration/cli/config/.prettierrc` and `.prettierrc` apply to `tests_integration/cli/config/editorconfig/file.shouldnotexist`, so the test wouldn't work even on master. Here's a way to confirm that: ```js const path = require('path') const assert = require('assert') const prettier = require('./') const file = './tests_integration/cli/config/editorconfig/file.shouldnotexist' console.log(prettier.resolveConfig.sync(file)) assert(prettier.resolveConfig.sync(file) === null) ```
2017-12-05 01:28:27 +03:00
Use `prettier.resolveConfig.sync(filePath [, options])` if you'd like to use sync version.
## `prettier.resolveConfigFile([filePath])`
`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 21: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.
The search starts at `process.cwd()`, or at `filePath` if provided. Please see the [cosmiconfig docs](https://github.com/davidtheclark/cosmiconfig#explorersearch) for details on how the resolving works.
```js
prettier.resolveConfigFile().then(filePath => {
prettier.resolveConfig(filePath).then(options => {
const formatted = prettier.format(text, options);
});
});
```
Use `prettier.resolveConfigFile.sync([filePath])` if you'd like to use sync version.
## `prettier.clearConfigCache()`
As you repeatedly call `resolveConfig`, the file system structure will be 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(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:
```typescript
{
ignored: boolean,
inferredParser: string | null,
}
```
The promise will be rejected if the type of `filePath` is not `string`.
Setting `options.ignorePath` (`string`) and `options.withNodeModules` (`boolean`) influence the value of `ignored` (`false` by default).
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 `false`), Prettier will resolve the configuration for the given `filePath`. This is useful, for example, when the `inferredParser` might be overridden for a subset of files.
Use `prettier.getFileInfo.sync(filePath [, options])` if you'd like to use sync version.
## `prettier.getSupportInfo([version])`
Returns an object representing the parsers, languages and file types Prettier supports.
If `version` is provided (e.g. `"1.5.0"`), information for that version will be returned, otherwise information for the current version will be returned.
The support information looks like this:
```typescript
{
languages: Array<{
name: string,
since?: string,
parsers: string[],
group?: string,
2018-08-08 18:47:49 +03:00
tmScope?: string,
aceMode?: string,
codemirrorMode?: string,
codemirrorMimeType?: string,
aliases?: string[],
2018-08-08 18:47:49 +03:00
extensions?: string[],
filenames?: string[],
2018-08-08 18:47:49 +03:00
linguistLanguageId?: number,
vscodeLanguageIds?: string[],
}>
}
```
## Custom Parser API
If you need to make modifications to the AST (such as codemods), or you want to provide an alternate parser, you can do so by setting the `parser` option to a function. The function signature of the parser function is:
```js
(text: string, parsers: object, options: object) => AST;
```
Prettier's built-in parsers are exposed as properties on the `parsers` argument.
```js
prettier.format("lodash ( )", {
2018-12-27 16:05:19 +03:00
parser(text, { babel }) {
const ast = babel(text);
ast.program.body[0].expression.callee.name = "_";
return ast;
}
});
// -> "_();\n"
```
The `--parser` CLI option may be a path to a node.js module exporting a parse function.