Prettier
Prettier is an opinionated code formatter that enforces a consistent style by parsing your code and re-printing it with its own rules, taking maximum line length into account. The current stable version is 3.8.3, and it receives frequent patch and minor releases, often including support for new language versions or bug fixes.
Common errors
-
Error: Prettier `format` functions must be passed a `parser` option or the file type must be detectable.
cause The `prettier.format()` function was called without a `parser` option and could not infer the language from the input.fixAdd a `parser` option to the format call, e.g., `prettier.format(code, { parser: 'babel' });`. -
Error [ERR_REQUIRE_ESM]: require() of ES Module <path>/node_modules/prettier-plugin-xyz/index.mjs from <path>/node_modules/prettier/index.js not supported.
cause Attempting to load an ES Module (ESM) Prettier plugin using a CommonJS `require()` context. Prettier 3.x plugins must be ESM.fixEnsure your project is set up to load ESM plugins correctly, or check that your plugin is compatible with Prettier 3.x's ESM-only plugin requirement. This might involve updating your `prettier.config.js` to be an ESM file or using `import` statements if your main config file is also ESM. -
Cannot find module 'prettier'
cause The `prettier` package is not installed or not resolvable in the current project's `node_modules`.fixInstall Prettier using `npm install prettier` or `yarn add prettier`. -
Error: Could not resolve a config for "...".
cause Prettier could not find a configuration file (e.g., `.prettierrc`, `prettier.config.js`) for the specified file path, or the configuration file is invalid.fixCreate a valid Prettier configuration file in the project root or specify options directly via CLI flags or API parameters.
Warnings
- breaking Prettier 3.x requires Node.js version 14 or higher.
- breaking Prettier 3.x plugins must be written as ES Modules (ESM). CommonJS plugins will fail to load.
- gotcha Prettier's opinionated formatting can lead to conflicts with existing manual style guides or other linters (e.g., ESLint).
- gotcha When using the `format` API function, a `parser` option is often required if the input code's language cannot be automatically detected.
Install
-
npm install prettier -
yarn add prettier -
pnpm add prettier
Imports
- prettier
import prettier from 'prettier';
Quickstart
import { format } from 'prettier';
async function run() {
const code = 'function foo() { return "bar"; }';
const formattedCode = await format(code, { parser: 'babel' });
console.log(formattedCode);
// Expected output:
// function foo() {
// return "bar";
// }
}
run();