or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-prettier-eslint

Formats your JavaScript using prettier followed by eslint --fix

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/prettier-eslint@16.4.x

To install, run

npx @tessl/cli install tessl/npm-prettier-eslint@16.4.0

0

# prettier-eslint

1

2

prettier-eslint is a code formatting tool that combines the power of Prettier's opinionated formatting with ESLint's configurable rule system. It formats JavaScript, TypeScript, Vue, and Svelte code by first applying Prettier formatting, then running ESLint with the `--fix` flag to apply project-specific linting rules and coding standards.

3

4

## Package Information

5

6

- **Package Name**: prettier-eslint

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install prettier-eslint`

10

11

## Core Imports

12

13

```javascript

14

const format = require('prettier-eslint');

15

const { format, analyze } = require('prettier-eslint');

16

```

17

18

ES Modules (for TypeScript projects):

19

20

```typescript

21

import prettierEslint from 'prettier-eslint';

22

import { format, analyze, getOptionsForFormatting, requireModule, getESLint } from 'prettier-eslint';

23

import type { FormatOptions, ESLintConfig, LogLevel, PrettierOptions } from 'prettier-eslint';

24

```

25

26

Type imports for advanced usage:

27

28

```typescript

29

import type { Linter } from 'eslint';

30

import type { ESLint } from 'eslint';

31

```

32

33

## Basic Usage

34

35

```javascript

36

const format = require('prettier-eslint');

37

38

const sourceCode = 'const {foo} = bar';

39

40

const options = {

41

text: sourceCode,

42

eslintConfig: {

43

parserOptions: {

44

ecmaVersion: 2017,

45

},

46

rules: {

47

semi: ['error', 'never'],

48

},

49

},

50

prettierOptions: {

51

bracketSpacing: true,

52

},

53

};

54

55

const formatted = await format(options);

56

console.log(formatted); // "const { foo } = bar"

57

```

58

59

**Alternative usage with file path:**

60

61

```javascript

62

const format = require('prettier-eslint');

63

64

// Format a file directly - ESLint config will be auto-resolved

65

const formatted = await format({

66

filePath: './src/component.js',

67

prettierOptions: {

68

printWidth: 100

69

}

70

});

71

```

72

73

**Note:** The module exports `format` as the default export, so `require('prettier-eslint')` returns the format function directly. Named exports are also available for `format` and `analyze`.

74

75

## Capabilities

76

77

### Code Formatting

78

79

The primary function that formats code using Prettier followed by ESLint --fix.

80

81

```typescript { .api }

82

/**

83

* Formats the text with Prettier and then ESLint while obeying the user's configuration

84

* @param options - Configuration options for formatting

85

* @returns Promise resolving to the formatted string

86

*/

87

function format(options: FormatOptions): Promise<string>;

88

```

89

90

**Usage Example:**

91

92

```typescript

93

import { format } from 'prettier-eslint';

94

95

const result = await format({

96

text: 'function hello(){console.log("world")}',

97

eslintConfig: {

98

rules: {

99

semi: ['error', 'always'],

100

quotes: ['error', 'single']

101

}

102

},

103

prettierOptions: {

104

singleQuote: true,

105

semi: true

106

}

107

});

108

```

109

110

### Code Analysis

111

112

Analyzes and formats code, returning both the formatted output and ESLint linting messages.

113

114

```typescript { .api }

115

/**

116

* Analyzes and formats text with prettier and eslint, returning both output and messages

117

* @param options - Configuration options identical to format function

118

* @returns Promise resolving to object with formatted output and ESLint messages

119

*/

120

function analyze(options: FormatOptions): Promise<{

121

output: string;

122

messages: Linter.LintMessage[];

123

}>;

124

```

125

126

**Usage Example:**

127

128

```typescript

129

import { analyze } from 'prettier-eslint';

130

131

const result = await analyze({

132

text: 'const unused = 42; console.log("hello");',

133

eslintConfig: {

134

rules: {

135

'no-unused-vars': ['error'],

136

'no-console': ['warn']

137

}

138

}

139

});

140

141

console.log(result.output); // Formatted code

142

console.log(result.messages); // ESLint messages array

143

```

144

145

### Configuration Options

146

147

All formatting functions accept a comprehensive options object for fine-grained control.

148

149

```typescript { .api }

150

interface FormatOptions {

151

/** The source code to format */

152

text?: string;

153

/** The path of the file being formatted (can be used in lieu of text) */

154

filePath?: string;

155

/** ESLint configuration object */

156

eslintConfig?: ESLintConfig;

157

/** Path to the eslint module to use */

158

eslintPath?: string;

159

/** Prettier formatting options */

160

prettierOptions?: PrettierOptions;

161

/** Path to the prettier module to use */

162

prettierPath?: string;

163

/** Fallback Prettier options when values cannot be inferred from ESLint config */

164

fallbackPrettierOptions?: PrettierOptions;

165

/** Run Prettier after ESLint instead of before */

166

prettierLast?: boolean;

167

/** Logging level for debug output */

168

logLevel?: LogLevel;

169

}

170

```

171

172

**File Path Usage:**

173

174

```typescript

175

// Format a file directly

176

const result = await format({

177

filePath: './src/component.tsx',

178

// ESLint config will be automatically resolved for the file

179

prettierOptions: {

180

printWidth: 100

181

}

182

});

183

```

184

185

**Custom Module Paths:**

186

187

```typescript

188

const result = await format({

189

text: sourceCode,

190

eslintPath: './node_modules/eslint',

191

prettierPath: './node_modules/prettier',

192

eslintConfig: { /* config */ }

193

});

194

```

195

196

### ESLint Configuration

197

198

Extended ESLint configuration interface supporting both object and string array formats for globals.

199

200

```typescript { .api }

201

type ESLintOptions = Omit<

202

ESLint.Options,

203

'plugins' | 'reportUnusedDisableDirectives'

204

>;

205

206

interface ESLintConfig extends Omit<Linter.Config, 'globals'>, ESLintOptions {

207

/** ESLint globals configuration, supporting both object format and string tuple format */

208

globals?: ESLintConfigGlobals | [`${string}:${ESLintConfigGlobalValue}`];

209

/** Ignore patterns for files */

210

ignorePattern?: string[] | string;

211

/** File extensions to process with ESLint */

212

extensions?: string[];

213

}

214

215

type ESLintConfigGlobals = Linter.Config['globals'];

216

type ESLintConfigGlobalValue = 'readonly' | 'writable' | 'off';

217

```

218

219

**Globals Configuration:**

220

221

```typescript

222

// Object format

223

const config = {

224

globals: {

225

window: 'readonly',

226

document: 'readonly',

227

myGlobal: 'writable'

228

}

229

};

230

231

// String array format

232

const config = {

233

globals: ['window:readonly', 'document:readonly', 'myGlobal:writable']

234

};

235

```

236

237

### Prettier Options

238

239

Re-exported Prettier options interface for type safety.

240

241

```typescript { .api }

242

type PrettierOptions = import('prettier').Options;

243

```

244

245

Common Prettier options used with prettier-eslint:

246

247

```typescript

248

const prettierOptions = {

249

printWidth: 80,

250

tabWidth: 2,

251

useTabs: false,

252

semi: true,

253

singleQuote: true,

254

quoteProps: 'as-needed',

255

trailingComma: 'es5',

256

bracketSpacing: true,

257

bracketSameLine: false,

258

arrowParens: 'avoid',

259

parser: 'typescript'

260

};

261

```

262

263

### Logging Configuration

264

265

Control the verbosity of debugging output during the formatting process.

266

267

```typescript { .api }

268

type LogLevel = 'debug' | 'error' | 'info' | 'silent' | 'trace' | 'warn';

269

```

270

271

**Logging Usage:**

272

273

```typescript

274

const result = await format({

275

text: sourceCode,

276

logLevel: 'debug', // Enable detailed logging

277

eslintConfig: { /* config */ }

278

});

279

```

280

281

### Utility Functions

282

283

Core utility functions for advanced integration scenarios.

284

285

```typescript { .api }

286

/**

287

* Extracts and prepares formatting options for ESLint and Prettier

288

* @param eslintConfig - ESLint configuration

289

* @param prettierOptions - Prettier options (optional)

290

* @param fallbackPrettierOptions - Fallback Prettier options (optional)

291

* @returns Object containing processed eslint and prettier options

292

*/

293

function getOptionsForFormatting(

294

eslintConfig: ESLintConfig,

295

prettierOptions?: PrettierOptions,

296

fallbackPrettierOptions?: PrettierOptions

297

): {

298

eslint: ESLintConfig;

299

prettier: PrettierOptions;

300

};

301

302

/**

303

* Safely requires a module with error handling

304

* @param modulePath - Path to the module

305

* @param name - Name of the module for error messages

306

* @returns The required module

307

*/

308

function requireModule<T>(modulePath: string, name: string): T;

309

310

/**

311

* Creates ESLint instance with given path and options

312

* @param eslintPath - Path to ESLint module

313

* @param eslintOptions - ESLint configuration options

314

* @returns ESLint instance

315

*/

316

function getESLint(eslintPath: string, eslintOptions: ESLintOptions): ESLint;

317

```

318

319

### Internal Types

320

321

Additional type definitions used by the library.

322

323

```typescript { .api }

324

/** Input structure for internal prettify function */

325

interface PrettifyInput {

326

output: string;

327

messages: Linter.LintMessage[];

328

}

329

330

/** Utility type for string literals with fallback */

331

type StringLiteral<T> = T | (string & { _?: never });

332

333

/** Option getter structure for mapping ESLint rules to Prettier options */

334

interface OptionGetter {

335

ruleValue: (rules?: Partial<Linter.RulesRecord>) => StringLiteral<Linter.RuleEntry> | undefined;

336

ruleValueToPrettierOption: (...args: any[]) => unknown;

337

}

338

339

/** Value type for ESLint config globals */

340

type ESLintConfigGlobalValue = 'readonly' | 'writable' | 'off';

341

342

/** Helper type for extracting values from objects */

343

type ValueOf<T> = T[keyof T];

344

```

345

346

## Supported File Types

347

348

prettier-eslint automatically handles the following file extensions:

349

350

- **JavaScript**: `.js`, `.jsx`, `.mjs`, `.cjs`

351

- **TypeScript**: `.ts`, `.tsx`, `.mts`, `.cts`

352

- **Vue**: `.vue` (requires vue-eslint-parser)

353

- **Svelte**: `.svelte` (requires svelte-eslint-parser and prettier-plugin-svelte)

354

355

For unsupported file extensions, only Prettier formatting is applied (ESLint is skipped).

356

357

## Parser Configuration

358

359

prettier-eslint automatically configures appropriate parsers based on file extensions:

360

361

```typescript

362

// Automatic parser selection

363

'.ts', '.tsx' → '@typescript-eslint/parser'

364

'.vue' → 'vue-eslint-parser'

365

'.svelte' → 'svelte-eslint-parser'

366

```

367

368

## Error Handling

369

370

Both `format` and `analyze` functions can throw errors in the following scenarios:

371

372

- **File not found**: When `filePath` is specified but file doesn't exist

373

- **Invalid ESLint config**: When ESLint configuration is malformed

374

- **Parser errors**: When code cannot be parsed by the specified parser

375

- **Module resolution errors**: When eslintPath or prettierPath cannot be resolved

376

377

Always wrap calls in try-catch blocks:

378

379

```typescript

380

try {

381

const result = await format({

382

filePath: './src/component.js',

383

eslintConfig: { /* config */ }

384

});

385

} catch (error) {

386

console.error('Formatting failed:', error.message);

387

}

388

```

389

390

## Integration Examples

391

392

### Gulp Integration

393

394

```javascript

395

const through = require('through2');

396

const prettierEslint = require('prettier-eslint');

397

398

function createFormatterStream(options = {}) {

399

return through.obj(async function(file, enc, callback) {

400

if (file.isNull()) {

401

return callback(null, file);

402

}

403

404

try {

405

const formatted = await prettierEslint({

406

text: file.contents.toString(),

407

filePath: file.path,

408

...options

409

});

410

411

file.contents = Buffer.from(formatted);

412

callback(null, file);

413

} catch (error) {

414

callback(error);

415

}

416

});

417

}

418

419

gulp.task('format', () =>

420

gulp.src('src/**/*.js')

421

.pipe(createFormatterStream({

422

eslintConfig: {

423

extends: ['eslint:recommended']

424

}

425

}))

426

.pipe(gulp.dest('src/'))

427

);

428

```

429

430

### CLI Tool Integration

431

432

```javascript

433

const fs = require('fs');

434

const path = require('path');

435

const { format } = require('prettier-eslint');

436

437

async function formatFile(filePath) {

438

const text = fs.readFileSync(filePath, 'utf8');

439

440

const formatted = await format({

441

text,

442

filePath,

443

// Let ESLint find the config automatically

444

logLevel: 'warn'

445

});

446

447

fs.writeFileSync(filePath, formatted);

448

console.log(`Formatted: ${filePath}`);

449

}

450

451

// Usage

452

formatFile('./src/index.js');

453

```