Update docs (#13309)

This commit is contained in:
fisker Cheung authored and GitHub committed 2022-09-26 19:28:43 +08:00
1 parent 04faada98b
commit 822f354ceb
7 files changed
+153 -70

No files matched your search

+7
View File
@@ -45,6 +45,13 @@ jobs:
- name: Lint workflow files
run: yarn lint:actionlint
- name: Lint docs code block
# TODO: Lint files in `website/versioned_docs/version-stable` too
run: yarn "docs/**/*.md"
env:
# Make Prettier throws on embeded format
PRETTIER_DEBUG: true
- name: Validate renovate config
run: npx --package renovate -c renovate-config-validator
+6 -6
View File
@@ -6,7 +6,7 @@ title: API
If you want to run Prettier programmatically, check this page out.
```js
const prettier = require("prettier");
import * as prettier from "prettier";
```
## `prettier.format(source, options)`
@@ -15,7 +15,7 @@ const prettier = require("prettier");
```js
await prettier.format("foo ( );", { semi: false, parser: "babel" });
// -> "foo()"
// -> 'foo()\n'
```
## `prettier.check(source [, options])`
@@ -81,10 +81,10 @@ When Prettier loads configuration files and plugins, the file system structure i
`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
```ts
{
ignored: boolean,
inferredParser: string | null,
ignored: boolean;
inferredParser: string | null;
}
```
@@ -104,7 +104,7 @@ Returns a promise which resolves to an object representing the options, parsers,
The support information looks like this:
```typescript
```ts
{
languages: Array<{
name: string;
+23 -17
View File
@@ -35,10 +35,12 @@ See below for examples.
<script src="https://unpkg.com/prettier@2.7.1/standalone.js"></script>
<script src="https://unpkg.com/prettier@2.7.1/parser-graphql.js"></script>
<script>
prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins: prettierPlugins,
});
(async () => {
const formatted = await prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins: prettierPlugins,
});
})();
</script>
```
@@ -51,7 +53,7 @@ Note that the [`unpkg` field](https://unpkg.com/#examples) in Prettier’s `pack
import * as prettier from "https://unpkg.com/prettier@2.7.1/esm/standalone.mjs";
import parserGraphql from "https://unpkg.com/prettier@2.7.1/esm/parser-graphql.mjs";
prettier.format("type Query { hello: String }", {
const formatted = await prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins: [parserGraphql],
});
@@ -64,8 +66,8 @@ Note that the [`unpkg` field](https://unpkg.com/#examples) in Prettier’s `pack
define([
"https://unpkg.com/prettier@2.7.1/standalone.js",
"https://unpkg.com/prettier@2.7.1/parser-graphql.js",
], (prettier, ...plugins) => {
prettier.format("type Query { hello: String }", {
], async (prettier, ...plugins) => {
const formatted = await prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins,
});
@@ -77,10 +79,12 @@ define([
```js
const prettier = require("prettier/standalone");
const plugins = [require("prettier/parser-graphql")];
prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins,
});
(async () => {
const formatted = await prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins,
});
})();
```
This syntax doesn’t necessarily work in the browser, but it can be used when bundling the code with browserify, Rollup, webpack, or another bundler.
@@ -90,10 +94,12 @@ This syntax doesn’t necessarily work in the browser, but it can be used when b
```js
importScripts("https://unpkg.com/prettier@2.7.1/standalone.js");
importScripts("https://unpkg.com/prettier@2.7.1/parser-graphql.js");
prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins: prettierPlugins,
});
(async () => {
const formatted = await prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins: prettierPlugins,
});
})();
```
## Parser plugins for embedded code
@@ -106,7 +112,7 @@ If you want to format [embedded code](options.md#embedded-language-formatting),
import parserBabel from "https://unpkg.com/prettier@2.7.1/esm/parser-babel.mjs";
console.log(
prettier.format("const html=/* HTML */ `<DIV> </DIV>`", {
await prettier.format("const html=/* HTML */ `<DIV> </DIV>`", {
parser: "babel",
plugins: [parserBabel],
})
@@ -124,7 +130,7 @@ The HTML code embedded in JavaScript stays unformatted because the `html` parser
import parserHtml from "https://unpkg.com/prettier@2.7.1/esm/parser-html.mjs";
console.log(
prettier.format("const html=/* HTML */ `<DIV> </DIV>`", {
await prettier.format("const html=/* HTML */ `<DIV> </DIV>`", {
parser: "babel",
plugins: [parserBabel, parserHtml],
})
+13 -13
View File
@@ -16,7 +16,7 @@ To format a file in-place, use `--write`. (Note: This overwrites your files!)
In practice, this may look something like:
```bash
prettier --write .
prettier . --write
```
This command formats all files supported by Prettier in the current directory and its subdirectories.
@@ -26,7 +26,7 @@ It’s recommended to always make sure that `prettier --write .` only formats wh
A more complicated example:
```bash
prettier --single-quote --trailing-comma all --write docs package.json "{app,__{tests,mocks}__}/**/*.js"
prettier docs package.json "{app,__{tests,mocks}__}/**/*.js" --write --single-quote --trailing-comma all
```
> Don’t forget the **quotes** around the globs! The quotes make sure that Prettier CLI expands the globs rather than your shell, which is important for cross-platform usage.
@@ -53,7 +53,7 @@ When you want to check if your files are formatted, you can run Prettier with th
This will output a human-friendly message and a list of unformatted files, if any.
```bash
prettier --check "src/**/*.js"
prettier . --check
```
Console output if all files are formatted:
@@ -95,15 +95,15 @@ If you're worried that Prettier will change the correctness of your code, add `-
If you are repeatedly formatting individual files with `prettier`, you will incur a small performance cost when Prettier attempts to look up a [configuration file](configuration.md). In order to skip this, you may ask Prettier to find the config file once, and re-use it later on.
```bash
prettier --find-config-path ./my/file.js
./my/.prettierrc
```console
$ prettier --find-config-path path/to/file.js
path/to/.prettierrc
```
This will provide you with a path to the configuration file, which you can pass to `--config`:
```bash
prettier --config ./my/.prettierrc --write ./my/file.js
prettier path/to/file.js --write --config path/to/.prettierrc
```
You can also use `--config` if your configuration file lives somewhere where Prettier cannot find it, such as a `config/` directory.
@@ -119,7 +119,7 @@ Path to a file containing patterns that describe files to ignore. By default, Pr
Another useful flag is `--list-different` (or `-l`) which prints the filenames of files that are different from Prettier formatting. If there are differences the script errors out, which is useful in a CI scenario.
```bash
prettier --single-quote --list-different "src/**/*.js"
prettier . --single-quote --list-different
```
You can also use [`--check`](cli.md#--check) flag, which works the same way as `--list-different`, but also prints a human-friendly summary message to stdout.
@@ -193,8 +193,8 @@ $ cat abc.css | prettier --stdin-filepath abc.css
With `--ignore-unknown` (or `-u`), prettier will ignore unknown files matched by patterns.
```console
$ prettier "**/*" --write --ignore-unknown
```bash
prettier "**/*" --write --ignore-unknown
```
## `--no-error-on-unmatched-pattern`
@@ -216,7 +216,7 @@ If this option is enabled, the following values are used as cache keys and the f
- (if `--cache-strategy` is `content`) content of the file
```bash
prettier --write --cache src
prettier . --write --cache
```
Running Prettier without `--cache` will delete the cache.
@@ -232,7 +232,7 @@ Path to the cache file location used by `--cache` flag. If you don't explicit `-
If a file path is passed, that file is used as the cache file.
```bash
prettier --write --cache --cache-location=my_cache_file src
prettier . --write --cache --cache-location=path/to/cache-file
```
## `--cache-strategy`
@@ -244,5 +244,5 @@ In general, `metadata` is faster. However, `content` is useful for updating the
If no strategy is specified, `content` will be used.
```bash
prettier --write --cache --cache-strategy metadata src
prettier . --write --cache --cache-strategy metadata
```
+5 -5
View File
@@ -13,13 +13,13 @@ To exclude files from formatting, create a `.prettierignore` file in the root of
Example:
```
```text
# Ignore artifacts:
build
coverage
# Ignore all HTML files:
*.html
**/*.html
```
It’s recommended to have a `.prettierignore` in your project! This way you can run `prettier --write .` to make sure that everything is formatted (without mangling files you don’t want, or choking on generated files). And – your editor will know which files _not_ to format!
@@ -28,7 +28,7 @@ By default prettier ignores files in version control systems directories (".git"
So by default it will be
```js
```text
**/.git
**/.svn
**/.hg
@@ -37,7 +37,7 @@ So by default it will be
and
```js
```text
**/.git
**/.svn
**/.hg
@@ -186,7 +186,7 @@ hello: world
For one-off commands, when you want to exclude some files without adding them to `.prettierignore`, negative patterns can come in handy:
```bash
prettier --write . '!**/*.{js,jsx,vue}'
prettier . "!**/*.{js,jsx,vue}" --write
```
See [fast-glob](https://prettier.io/docs/en/cli.html#file-patterns) to learn more about advanced glob syntax.
+4 -4
View File
@@ -30,7 +30,7 @@ echo {}> .prettierrc.json
Next, create a [.prettierignore](ignore.md) file to let the Prettier CLI and editors know which files to _not_ format. Here’s an example:
```
```text
# Ignore artifacts:
build
coverage
@@ -46,7 +46,7 @@ Now, format all files with Prettier:
<!--npm-->
```bash
npx prettier --write .
npx prettier . --write
```
> What is that `npx` thing? `npx` ships with `npm` and lets you run locally installed tools. We’ll leave off the `npx` part for brevity throughout the rest of this file!
@@ -56,7 +56,7 @@ npx prettier --write .
<!--yarn-->
```bash
yarn prettier --write .
yarn prettier . --write
```
> What is `yarn` doing at the start? `yarn prettier` runs the locally installed version of Prettier. We’ll leave off the `yarn` part for brevity throughout the rest of this file!
@@ -68,7 +68,7 @@ yarn prettier --write .
If you have a CI setup, run the following as part of it to make sure that everyone runs Prettier. This avoids merge conflicts and other collaboration issues!
```bash
npx prettier --check .
npx prettier . --check
```
`--check` is like `--write`, but only checks that files are already formatted, rather than overwriting them. `prettier --write` and `prettier --check` are the most common ways to run Prettier.
+95 -25
View File
@@ -486,54 +486,124 @@ The `--debug-print-comments` CLI flag can help with debugging comment attachment
Example:
```js
options: {
openingBraceNewLine: {
type: "boolean",
category: "Global",
default: true,
description: "Move open brace for code blocks onto new line."
}
}
export default {
// ... plugin implementation
options: {
openingBraceNewLine: {
type: "boolean",
category: "Global",
default: true,
description: "Move open brace for code blocks onto new line.",
},
},
};
```
### `defaultOptions`
If your plugin requires different default values for some of Prettier’s core options, you can specify them in `defaultOptions`:
```
defaultOptions: {
tabWidth: 4
}
```js
export default {
// ... plugin implementation
defaultOptions: {
tabWidth: 4,
},
};
```
### Utility functions
A `util` module from Prettier core is considered a private API and is not meant to be consumed by plugins. Instead, the `util-shared` module provides the following limited set of utility functions for plugins:
<!-- prettier-ignore -->
```ts
type Quote = '"' | "'";
type SkipOptions = { backwards?: boolean };
function getMaxContinuousCount(str: string, target: string): number;
function getStringWidth(text: string): number;
function getAlignmentSize(value: string, tabWidth: number, startIndex?: number): number;
function getAlignmentSize(
value: string,
tabWidth: number,
startIndex?: number
): number;
function getIndentSize(value: string, tabWidth: number): number;
function skip(chars: string | RegExp): (text: string, index: number | false, opts?: SkipOptions) => number | false;
function skipWhitespace(text: string, index: number | false, opts?: SkipOptions): number | false;
function skipSpaces(text: string, index: number | false, opts?: SkipOptions): number | false;
function skipToLineEnd(text: string, index: number | false, opts?: SkipOptions): number | false;
function skipEverythingButNewLine(text: string, index: number | false, opts?: SkipOptions): number | false;
function skip(
chars: string | RegExp
): (text: string, index: number | false, opts?: SkipOptions) => number | false;
function skipWhitespace(
text: string,
index: number | false,
opts?: SkipOptions
): number | false;
function skipSpaces(
text: string,
index: number | false,
opts?: SkipOptions
): number | false;
function skipToLineEnd(
text: string,
index: number | false,
opts?: SkipOptions
): number | false;
function skipEverythingButNewLine(
text: string,
index: number | false,
opts?: SkipOptions
): number | false;
function skipInlineComment(text: string, index: number | false): number | false;
function skipTrailingComment(text: string, index: number | false): number | false;
function skipNewline(text: string, index: number | false, opts?: SkipOptions): number | false;
function skipTrailingComment(
text: string,
index: number | false
): number | false;
function skipNewline(
text: string,
index: number | false,
opts?: SkipOptions
): number | false;
function hasNewline(text: string, index: number, opts?: SkipOptions): boolean;
function hasNewlineInRange(text: string, start: number, end: number): boolean;
function hasSpaces(text: string, index: number, opts?: SkipOptions): boolean;
function makeString(rawContent: string, enclosingQuote: Quote, unescapeUnnecessaryEscapes?: boolean): string;
function getNextNonSpaceNonCommentCharacterIndex<N>(text: string, node: N, locEnd: (node: N) => number): number | false;
function makeString(
rawContent: string,
enclosingQuote: Quote,
unescapeUnnecessaryEscapes?: boolean
): string;
function getNextNonSpaceNonCommentCharacterIndex<N>(
text: string,
node: N,
locEnd: (node: N) => number
): number | false;
function isNextLineEmptyAfterIndex(text: string, index: number): boolean;
function isNextLineEmpty<N>(text: string, node: N, locEnd: (node: N) => number): boolean;
function isPreviousLineEmpty<N>(text: string, node: N, locStart: (node: N) => number): boolean;
function isNextLineEmpty<N>(
text: string,
node: N,
locEnd: (node: N) => number
): boolean;
function isPreviousLineEmpty<N>(
text: string,
node: N,
locStart: (node: N) => number
): boolean;
```
### Tutorials