Prettier is an opinionated code formatter that enforces consistent style across multiple languages including JavaScript, TypeScript, Flow, JSX, JSON, CSS, SCSS, Less, HTML, Vue, Angular, GraphQL, Markdown, and YAML.
npx @tessl/cli install tessl/npm-prettier@3.6.00
# Prettier
1
2
## Package Information
3
4
- **Name**: prettier
5
- **Type**: npm package
6
- **Language**: JavaScript/TypeScript
7
- **License**: MIT
8
- **Version**: 3.6.2
9
10
## Installation
11
12
```bash
13
npm install prettier
14
# or
15
yarn add prettier
16
# or
17
pnpm add prettier
18
```
19
20
## Core Imports
21
22
### ESM (Recommended)
23
```javascript { .api }
24
import * as prettier from 'prettier';
25
// or
26
import { format, formatWithCursor, check, resolveConfig, getSupportInfo } from 'prettier';
27
```
28
29
### CommonJS
30
```javascript { .api }
31
const prettier = require('prettier');
32
// or
33
const { format, formatWithCursor, check, resolveConfig, getSupportInfo } = require('prettier');
34
```
35
36
### Browser/Standalone
37
```javascript { .api }
38
import * as prettier from 'prettier/standalone';
39
// Requires plugins to be imported separately for each language
40
```
41
42
## Basic Usage
43
44
### Format Code
45
```javascript { .api }
46
const formatted = await prettier.format('const x={a:1,b:2}', {
47
parser: 'babel',
48
semi: false,
49
singleQuote: true
50
});
51
// Result: "const x = { a: 1, b: 2 }"
52
```
53
54
### Check if Code is Formatted
55
```javascript { .api }
56
const isFormatted = await prettier.check('const x = { a: 1, b: 2 }', {
57
parser: 'babel'
58
});
59
// Result: true
60
```
61
62
### Resolve Configuration
63
```javascript { .api }
64
const config = await prettier.resolveConfig('/path/to/file.js');
65
// Result: { semi: true, singleQuote: false, ... } or null
66
```
67
68
## Capabilities
69
70
Prettier provides comprehensive code formatting capabilities organized into these areas:
71
72
### Core Formatting Functions
73
Format code with full control over cursor position, check formatting status, and integrate with editors.
74
75
```javascript { .api }
76
// Format with cursor tracking for editor integrations
77
const result = await prettier.formatWithCursor(code, {
78
cursorOffset: 10,
79
parser: 'babel'
80
});
81
// result: { formatted: string, cursorOffset: number }
82
83
// Check if code needs formatting
84
const needsFormatting = !(await prettier.check(code, { parser: 'babel' }));
85
```
86
87
**[Core Formatting Functions](./core-formatting.md)**
88
89
### Configuration Resolution
90
Discover and resolve Prettier configuration files with support for EditorConfig integration.
91
92
```javascript { .api }
93
// Resolve configuration for a specific file
94
const config = await prettier.resolveConfig('/path/to/file.js', {
95
editorconfig: true,
96
useCache: true
97
});
98
99
// Find configuration file path
100
const configPath = await prettier.resolveConfigFile('/path/to/project');
101
102
// Clear configuration cache
103
await prettier.clearConfigCache();
104
```
105
106
**[Configuration Resolution](./configuration.md)**
107
108
### File Analysis and Language Support
109
Analyze files to determine parsers, check ignore status, and discover supported languages.
110
111
```javascript { .api }
112
// Get file information including inferred parser
113
const fileInfo = await prettier.getFileInfo('/path/to/file.js', {
114
resolveConfig: true,
115
plugins: []
116
});
117
// result: { ignored: boolean, inferredParser: string | null }
118
119
// Get supported languages and options
120
const supportInfo = await prettier.getSupportInfo({
121
showDeprecated: false,
122
plugins: []
123
});
124
// result: { languages: SupportLanguage[], options: SupportOption[] }
125
```
126
127
**[File Analysis and Language Support](./file-analysis.md)**
128
129
### Document Builder API (Advanced Plugin Development)
130
Low-level document building primitives for creating custom formatters and plugins.
131
132
```javascript { .api }
133
import { doc } from 'prettier';
134
135
// Build formatting documents
136
const document = doc.builders.group([
137
'if (',
138
doc.builders.indent([doc.builders.line, 'condition']),
139
doc.builders.line,
140
')'
141
]);
142
143
// Print document to string
144
const { formatted } = doc.printer.printDocToString(document, {
145
printWidth: 80,
146
tabWidth: 2
147
});
148
```
149
150
**[Document Builder API](./document-builders.md)**
151
152
### Utility Functions
153
Text processing, AST navigation, and comment manipulation utilities for advanced use cases.
154
155
```javascript { .api }
156
import { util } from 'prettier';
157
158
// String and position utilities
159
const width = util.getStringWidth('text');
160
const nextChar = util.getNextNonSpaceNonCommentCharacter(text, 0);
161
const hasNewLine = util.hasNewline(text, 10);
162
163
// Comment utilities
164
util.addLeadingComment(node, comment);
165
util.addTrailingComment(node, comment);
166
```
167
168
**[Utility Functions](./utilities.md)**
169
170
### Debug and Internal APIs (Advanced)
171
Low-level debugging APIs for development, CLI tools, and advanced integrations. These functions provide access to Prettier's internal parsing and formatting pipeline.
172
173
```javascript { .api }
174
import prettier from 'prettier';
175
176
// Parse source code to AST without formatting
177
const ast = await prettier.__debug.parse(code, { parser: 'babel' });
178
179
// Format AST to intermediate document representation
180
const doc = await prettier.__debug.formatAST(ast, { parser: 'babel' });
181
182
// Format document object to final string output
183
const formatted = await prettier.__debug.formatDoc(doc, { printWidth: 80 });
184
185
// Convert source to document without formatting (for analysis)
186
const doc = await prettier.__debug.printToDoc(code, { parser: 'babel' });
187
188
// Print document to string with layout options
189
const result = await prettier.__debug.printDocToString(doc, {
190
printWidth: 80,
191
tabWidth: 2
192
});
193
// result: { formatted: string, cursorOffset?: number }
194
```
195
196
**Note:** Debug APIs are internal and may change between versions. Use with caution in production.
197
198
### Version Information
199
Get the current Prettier version for compatibility checks and debugging.
200
201
```javascript { .api }
202
import { version } from 'prettier';
203
204
console.log(version); // '3.6.2'
205
206
// Check version compatibility
207
const majorVersion = parseInt(version.split('.')[0]);
208
if (majorVersion >= 3) {
209
// Use newer APIs
210
}
211
```
212
213
## Supported Languages
214
215
Prettier supports formatting for the following languages out of the box:
216
217
- **JavaScript**: ES2015+, JSX, Flow, TypeScript
218
- **CSS**: CSS, SCSS, Less
219
- **Markup**: HTML, Vue, Angular templates, LWC
220
- **Data**: JSON, JSON5, JSONC, YAML
221
- **GraphQL**: Schema and query documents
222
- **Markdown**: CommonMark, GFM, MDX
223
- **Templates**: Handlebars/Glimmer
224
225
Additional languages can be supported through plugins.
226
227
## TypeScript Support
228
229
Prettier includes full TypeScript definitions and supports both ESM and CommonJS imports:
230
231
```typescript { .api }
232
import { format, Options, AST, Doc, AstPath, LiteralUnion } from 'prettier';
233
234
const options: Options = {
235
parser: 'typescript',
236
semi: false,
237
singleQuote: true
238
};
239
240
const formatted: string = await format(code, options);
241
```
242
243
### Advanced TypeScript Types
244
245
```typescript { .api }
246
// Utility type for string literals with fallback
247
export type LiteralUnion<T extends U, U = string> =
248
| T
249
| (Pick<U, never> & { _?: never | undefined });
250
251
// AST and Document types
252
export type AST = any;
253
export type Doc = doc.builders.Doc;
254
255
// Enhanced AstPath for AST traversal
256
export class AstPath<T = any> {
257
constructor(value: T);
258
259
// Navigation properties
260
get key(): string | null;
261
get index(): number | null;
262
get node(): T;
263
get parent(): T | null;
264
get grandparent(): T | null;
265
get isInArray(): boolean;
266
get siblings(): T[] | null;
267
get next(): T | null;
268
get previous(): T | null;
269
get isFirst(): boolean;
270
get isLast(): boolean;
271
get isRoot(): boolean;
272
get root(): T;
273
get ancestors(): T[];
274
275
// Traversal methods
276
callParent<U>(callback: (path: this) => U, count?: number): U;
277
match(...predicates: Array<(node: any, name: string | null, number: number | null) => boolean>): boolean;
278
call<U>(callback: (path: AstPath<T>, index: number, value: any) => U): U;
279
each(callback: (path: AstPath<T>, index: number, value: any) => void): void;
280
map<U>(callback: (path: AstPath<T>, index: number, value: any) => U): U[];
281
}
282
283
// Built-in parser names with literal union support
284
export type BuiltInParserName = LiteralUnion<
285
| "acorn" | "angular" | "babel-flow" | "babel-ts" | "babel"
286
| "css" | "espree" | "flow" | "glimmer" | "graphql" | "html"
287
| "json-stringify" | "json" | "json5" | "jsonc" | "less"
288
| "lwc" | "markdown" | "mdx" | "meriyah" | "mjml" | "scss"
289
| "typescript" | "vue" | "yaml"
290
>;
291
```
292
293
## Plugin System
294
295
Prettier supports plugins to extend language support and customize formatting behavior. Built-in languages are implemented as internal plugins, and external plugins can be loaded:
296
297
```javascript { .api }
298
import myPlugin from 'prettier-plugin-custom';
299
300
const formatted = await prettier.format(code, {
301
parser: 'custom',
302
plugins: [myPlugin]
303
});
304
```
305
306
### Plugin Development
307
Advanced plugin interfaces for creating custom parsers, printers, and language support.
308
309
```typescript { .api }
310
// Plugin interface with language support
311
interface Plugin<T = any> {
312
languages?: SupportLanguage[];
313
parsers?: { [parserName: string]: Parser<T> };
314
printers?: { [astFormat: string]: Printer<T> };
315
options?: SupportOptions;
316
defaultOptions?: Partial<RequiredOptions>;
317
}
318
319
// Parser implementation
320
interface Parser<T = any> {
321
parse: (text: string, options: ParserOptions<T>) => T | Promise<T>;
322
astFormat: string;
323
hasPragma?: (text: string) => boolean;
324
locStart: (node: T) => number;
325
locEnd: (node: T) => number;
326
}
327
```
328
329
**[Plugin Development Guide](./plugin-development.md)**