0
# Core Formatting Functions
1
2
The core formatting functions provide the main API for formatting code with Prettier. These functions handle code parsing, formatting, and result generation with full async support.
3
4
## Core Functions
5
6
### format
7
```javascript { .api }
8
async function format(source: string, options?: Options): Promise<string>
9
```
10
11
Format source code using Prettier with the specified options.
12
13
**Parameters:**
14
- `source` (string): The source code to format
15
- `options` (Options, optional): Formatting options and parser configuration
16
17
**Returns:** Promise resolving to formatted source code string
18
19
**Example:**
20
```javascript { .api }
21
const formatted = await prettier.format('const x={a:1,b:2}', {
22
parser: 'babel',
23
semi: false,
24
singleQuote: true,
25
printWidth: 80
26
});
27
// Result: "const x = { a: 1, b: 2 };\n"
28
```
29
30
### formatWithCursor
31
```javascript { .api }
32
async function formatWithCursor(source: string, options: CursorOptions): Promise<CursorResult>
33
```
34
35
Format source code while tracking cursor position. Essential for editor integrations to maintain cursor position after formatting.
36
37
**Parameters:**
38
- `source` (string): The source code to format
39
- `options` (CursorOptions): Formatting options including cursor position
40
41
**Returns:** Promise resolving to CursorResult with formatted code and new cursor position
42
43
**Types:**
44
```javascript { .api }
45
interface CursorOptions extends Options {
46
cursorOffset: number; // Position of cursor in original source
47
}
48
49
interface CursorResult {
50
formatted: string; // Formatted source code
51
cursorOffset: number; // New cursor position in formatted code
52
}
53
```
54
55
**Example:**
56
```javascript { .api }
57
const result = await prettier.formatWithCursor('const x={a:1,|b:2}', {
58
cursorOffset: 13, // Position marked with |
59
parser: 'babel',
60
semi: false
61
});
62
// result.formatted: "const x = { a: 1, b: 2 }\n"
63
// result.cursorOffset: 18 (adjusted position)
64
```
65
66
### check
67
```javascript { .api }
68
async function check(source: string, options?: Options): Promise<boolean>
69
```
70
71
Check if source code is already formatted according to Prettier rules. Equivalent to CLI `--list-different` flag.
72
73
**Parameters:**
74
- `source` (string): The source code to check
75
- `options` (Options, optional): Formatting options to use for comparison
76
77
**Returns:** Promise resolving to boolean - true if already formatted, false if formatting is needed
78
79
**Example:**
80
```javascript { .api }
81
const isFormatted = await prettier.check('const x = { a: 1, b: 2 };', {
82
parser: 'babel'
83
});
84
// Result: true
85
86
const needsFormatting = await prettier.check('const x={a:1,b:2}', {
87
parser: 'babel'
88
});
89
// Result: false
90
```
91
92
## Formatting Options
93
94
### Core Options
95
```javascript { .api }
96
interface Options {
97
// Parser and language
98
parser?: string; // Parser to use (babel, typescript, css, etc.)
99
filepath?: string; // File path for parser inference
100
101
// Code style
102
printWidth?: number; // Line length limit (default: 80)
103
tabWidth?: number; // Tab width (default: 2)
104
useTabs?: boolean; // Use tabs instead of spaces (default: false)
105
semi?: boolean; // Print semicolons (default: true)
106
singleQuote?: boolean; // Use single quotes (default: false)
107
jsxSingleQuote?: boolean; // Use single quotes in JSX (default: false)
108
quoteProps?: 'as-needed' | 'consistent' | 'preserve'; // Quote object properties
109
110
// Trailing commas
111
trailingComma?: 'none' | 'es5' | 'all'; // Trailing commas (default: 'all')
112
113
// Spacing and brackets
114
bracketSpacing?: boolean; // Spaces in object literals (default: true)
115
bracketSameLine?: boolean; // Put > on same line in multi-line elements
116
arrowParens?: 'avoid' | 'always'; // Parentheses around single arrow function param
117
objectWrap?: 'preserve' | 'collapse'; // How to wrap object literals (default: 'preserve')
118
119
// Range formatting
120
rangeStart?: number; // Format only a range (default: 0)
121
rangeEnd?: number; // Format only a range (default: Infinity)
122
123
// Pragmas
124
requirePragma?: boolean; // Only format files with @format pragma
125
insertPragma?: boolean; // Insert @format pragma in formatted files
126
checkIgnorePragma?: boolean; // Respect // prettier-ignore comments
127
128
// Prose
129
proseWrap?: 'always' | 'never' | 'preserve'; // Wrap prose (default: 'preserve')
130
131
// HTML/CSS specific
132
htmlWhitespaceSensitivity?: 'css' | 'strict' | 'ignore';
133
vueIndentScriptAndStyle?: boolean; // Indent <script> and <style> in Vue
134
135
// Line endings
136
endOfLine?: 'auto' | 'lf' | 'crlf' | 'cr'; // Line ending style
137
138
// Embedded languages
139
embeddedLanguageFormatting?: 'auto' | 'off'; // Format embedded code
140
141
// Experimental
142
singleAttributePerLine?: boolean; // One attribute per line in HTML/JSX
143
experimentalOperatorPosition?: 'start' | 'end'; // Operator position in binary expressions (default: 'end')
144
experimentalTernaries?: boolean; // Use curious ternary formatting (default: false)
145
146
// Plugins
147
plugins?: Array<string | Plugin>; // Plugins to load
148
}
149
```
150
151
## Parser Selection
152
153
Prettier automatically infers the parser from file extensions, but you can specify explicitly:
154
155
### JavaScript Parsers
156
```javascript { .api }
157
// Babel parser (recommended for modern JS/TS/JSX)
158
{ parser: 'babel' }
159
160
// TypeScript-specific parsers
161
{ parser: 'typescript' } // Standard TypeScript parser
162
{ parser: 'babel-ts' } // Babel TypeScript parser
163
164
// Flow parsers
165
{ parser: 'flow' } // Flow parser
166
{ parser: 'babel-flow' } // Babel Flow parser
167
168
// Alternative parsers
169
{ parser: 'acorn' } // Acorn parser
170
{ parser: 'espree' } // ESLint's parser
171
{ parser: 'meriyah' } // Fast parser
172
```
173
174
### CSS Parsers
175
```javascript { .api }
176
{ parser: 'css' } // Standard CSS
177
{ parser: 'scss' } // SCSS/Sass
178
{ parser: 'less' } // Less CSS
179
```
180
181
### Markup Parsers
182
```javascript { .api }
183
{ parser: 'html' } // HTML
184
{ parser: 'vue' } // Vue SFC
185
{ parser: 'angular' } // Angular templates
186
{ parser: 'lwc' } // Lightning Web Components
187
```
188
189
### Data Parsers
190
```javascript { .api }
191
{ parser: 'json' } // JSON
192
{ parser: 'json5' } // JSON5
193
{ parser: 'jsonc' } // JSON with comments
194
{ parser: 'json-stringify' } // JSON with stringify behavior
195
{ parser: 'yaml' } // YAML
196
```
197
198
### Other Parsers
199
```javascript { .api }
200
{ parser: 'graphql' } // GraphQL
201
{ parser: 'markdown' } // Markdown
202
{ parser: 'mdx' } // MDX (Markdown + JSX)
203
{ parser: 'glimmer' } // Handlebars/Glimmer templates
204
{ parser: 'mjml' } // MJML email templates
205
```
206
207
## Error Handling
208
209
All formatting functions can throw errors for invalid syntax or configuration:
210
211
```javascript { .api }
212
try {
213
const formatted = await prettier.format('invalid javascript syntax', {
214
parser: 'babel'
215
});
216
} catch (error) {
217
console.error('Formatting error:', error.message);
218
console.error('Location:', error.loc); // { start: { line, column }, end: { line, column } }
219
}
220
```
221
222
## Performance Considerations
223
224
- Use `check()` before `format()` to avoid unnecessary formatting
225
- Cache configuration resolution results when processing multiple files
226
- Consider using standalone build for browser applications
227
- Plugin loading has overhead - reuse formatter instances when possible
228
229
```javascript { .api }
230
// Efficient multi-file formatting
231
const config = await prettier.resolveConfig(firstFile);
232
const cachedConfig = { ...config, filepath: undefined }; // Remove filepath for reuse
233
234
for (const file of files) {
235
const needsFormatting = !(await prettier.check(file.content, {
236
...cachedConfig,
237
filepath: file.path
238
}));
239
240
if (needsFormatting) {
241
file.formatted = await prettier.format(file.content, {
242
...cachedConfig,
243
filepath: file.path
244
});
245
}
246
}
247
```