babel工具之@babel/code-frame(翻译)

3,293 阅读1分钟

安装

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

使用

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 | }

如果列号未知,可以省略它。

也可以在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 | };

选项

highlightCode

boolean, defaults to false.

切换将代码突出显示为终端的JavaScript的语法。

linesAbove

number, defaults to 2.

调整显示在错误上方的行数。

linesBelow

number, defaults to 3.

调整显示在错误下方的行数。

forceColor

boolean, defaults to false.

启用此选项可强制语法将代码突出显示为JavaScript(对于非终端);重写highlightCode。

message

string, otherwise nothing

传入要在代码中突出显示的位置旁边以内联方式显示的字符串(如果可能)。如果不能内联定位,它将被放在代码框的上方。

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

从以前的版本升级

在版本7之前,此模块公开的唯一API是用于单行和可选列指针的。旧API现在将记录一个弃用警告。

新的API接受一个location对象,类似于AST中可用的对象。

以下是已弃用(但仍可用)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);

要使用新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);