# @babel/代码框架
# 安装
- npm
npm install --save-dev @babel/code-frame
- yarn
yarn add --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 | }
如果列号未知,您可以省略它。
您还可以end在location.
JavaScript
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 (opens new window)
boolean, 默认为false.
将语法高亮显示为终端的 JavaScript。
# linesAbove (opens new window)
number, 默认为2.
调整显示在错误上方的行数。
# linesBelow (opens new window)
number, 默认为3.
调整显示在错误下方的行数。
# forceColor (opens new window)
boolean, 默认为false.
启用它以强制将代码语法高亮显示为 JavaScript(对于非终端);覆盖highlightCode.
# message (opens new window)
string, 否则什么都没有
传入要在代码中突出显示的位置旁边内联显示(如果可能)的字符串。如果不能内联定位,就会放在代码框上方。
1 | class Foo {
> 2 | constructor()
| ^ Missing {
3 | };
# 从以前的版本 (opens new window)
在版本 7 之前,此模块公开的唯一 API 是用于单行和可选列指针的。旧 API 现在将记录弃用警告。
新的 API 采用一个location对象,类似于 AST 中可用的对象。
这是已弃用(但仍然可用)API 的示例:
JavaScript
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 获得相同的突出显示:
JavaScript
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);