API
If you want to run Prettier programmatically, check this page out.
import * as prettier from "prettier";
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 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 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 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.
await prettier.formatWithCursor(" 1", { cursorOffset: 2, parser: "babel" });
// -> { formatted: '1;\n', cursorOffset: 1 }
prettier.resolveConfig(fileUrlOrPath [, options])
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, 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.
const text = await fs.readFile(filePath, "utf8");
const options = await prettier.resolveConfig(filePath);
const formatted = await prettier.format(text, {
...options,
filepath: filePath,
});
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_lineindent_styleindent_size/tab_widthmax_line_length
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:
- The path of the configuration file.