The installation

npm install --save-dev @babel/code-frame
Copy the code

use

import { codeFrameColumns } from '@babel/code-frame';

const rawLines = `class Foo {
  constructor()
}`;
const location = { start: { line: 2, column: 16 } };

const result = codeFrameColumns(rawLines, location, { /* options */ });

console.log(result);


  1 | class Foo {
> 2 |   constructor()
    |                ^
  3 | }
Copy the code

If the column number is unknown, it can be omitted.

You can also pass the end hash in location.

import { codeFrameColumns } from '@babel/code-frame'; const rawLines = `class Foo { constructor() { console.log("hello"); }} `; const location = { start: { line: 2, column: 17 }, end: { line: 4, column: 3 } }; const result = codeFrameColumns(rawLines, location, { /* options */ }); console.log(result); 1 | class Foo { > 2 | constructor() { | ^ > 3 | console.log("hello"); | ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ | | > 4} ^ ^ ^ 5 |};Copy the code

options

highlightCode

boolean, defaults to false.

Toggle JavaScript syntax that highlights code as terminals.

linesAbove

number, defaults to 2.

Adjusts the number of lines displayed above the error.

linesBelow

number, defaults to 3.

Adjust the number of lines displayed below the error.

forceColor

boolean, defaults to false.

Enabling this option forces syntax to highlight code as JavaScript (for non-terminals); Rewrite highlightCode.

message

string, otherwise nothing

Pass in the string to be displayed inline, if possible, next to the position to be highlighted in the code. If it cannot be positioned inline, it will be placed above the code box.

1 | class Foo {
> 2 |   constructor()
  |                ^ Missing {
3 | };
Copy the code

Upgrade from a previous version

Prior to version 7, the only API exposed by this module was for single-row and optional column Pointers. The old API will now log a deprecation warning.

The new API accepts a Location object, similar to those available in the AST.

Here is an example of a deprecated (but still available) API:

import codeFrame from '@babel/code-frame';

const rawLines = `class Foo {
  constructor()
}`;
const lineNumber = 2;
const colNumber = 16;

const result = codeFrame(rawLines, lineNumber, colNumber, { /* options */ });

console.log(result);
Copy the code

To get the same highlighting using the new API:

import { codeFrameColumns } from '@babel/code-frame';

const rawLines = `class Foo {
  constructor() {
    console.log("hello");
  }
}`;
const location = { start: { line: 2, column: 16 } };

const result = codeFrameColumns(rawLines, location, { /* options */ });

console.log(result);
Copy the code