babel-errors

raw JSON →
1.1.1 verified Sat Apr 25 auth: no javascript

A library for creating nicer error messages with code frames for Babel transformations and plugins. Current stable version 1.1.1 provides utilities like buildCodeFrameError, prettyError, wrapErrorWithCodeFrame, and createErrorWithLoc. Sporadically maintained, it differentiates from Babel's built-in error formatting by offering explicit functions to construct location-aware errors outside the plugin context.

error Error: Cannot find module 'babel-code-frame'
cause Missing peer dependency babel-code-frame.
fix
Run npm install babel-code-frame.
error TypeError: path.buildCodeFrameError is not a function
cause Trying to use babel-errors' buildCodeFrameError as a method on a Path object.
fix
Call buildCodeFrameError(path, message) as a standalone function.
error Uncaught TypeError: createErrorWithLoc is not a function
cause Importing as default instead of named export.
fix
Use import { createErrorWithLoc } from 'babel-errors'.
gotcha buildCodeFrameError requires a Babel NodePath object; passing a plain object will throw without clear error.
fix Ensure argument is a valid Babel Path (e.g., from traversal).
deprecated Function toErrorStack is deprecated; use error.stack or custom formatting instead.
fix Use error.stack or manual format.
gotcha wrapErrorWithCodeFrame only adds code frame if the error has line/column properties; otherwise returns original error silently.
fix Ensure error has loc property (use createErrorWithLoc).
npm install babel-errors
yarn add babel-errors
pnpm add babel-errors

Demonstrates creating errors with location and building code frame errors using babel-errors with a simple AST.

import { buildCodeFrameError, createErrorWithLoc } from 'babel-errors';
import { parse } from '@babel/parser';
import generate from '@babel/generator';

const code = 'const x = 1;';
const ast = parse(code, { sourceType: 'module' });
const { path } = ast;

// Throw an error with location
const line = 1, column = 6;
const err = createErrorWithLoc('Test error at position', line, column);
console.log(err.message);
console.log('Name:', err.name); // BabelError

// Use buildCodeFrameError with a path
try {
  buildCodeFrameError(path, 'Error with this Path');
} catch (e) {
  console.log(e.message);
}