@babel/code-frame
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
安装
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/code-frame
yarn add --dev @babel/code-frame
pnpm add --save-dev @babel/code-frame
bun add --dev @babel/code-frame
用法
codeFrameColumns
codeFrameColumns 函数可为代码片段添加行号标记,并在指定位置显示定位标记。
该函数还支持可选语法高亮功能,默认适配输出终端的显示能力。
JavaScript
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 参数中传递 end 对象。
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
boolean,默认值 false
控制是否为终端环境启用 JavaScript 语法高亮
linesAbove
number,默认值 2
设置错误位置上方显示的代码行数
linesBelow
number,默认值 3
设置错误位置下方显示的代码行数
forceColor
boolean,默认值 false
强制对代码进行 JavaScript 语法高亮(适用于非终端环境),优先级高于 highlightCode
message
string,未设置时不显示
传入字符串可在代码高亮位置旁内联显示(若位置允许)。若无法内联显示,将展示在代码框上方
1 | class Foo {
> 2 | constructor()
| ^ Missing {
3 | };
highlight
highlight 函数可为终端显示的代码片段添加语法高亮
JavaScript
import { highlight } from "@babel/code-frame";
const code = `class Foo {
constructor()
}`;
const result = highlight(code);
console.log(result);
JavaScript
class Foo {
constructor()
}
从 @babel/highlight 迁移
highlight 功能最初独立封装在 @babel/highlight 包中
迁移方式如下:
Using @babel/highlight | Using @babel/code-frame |
|---|---|
JavaScript | JavaScript |
JavaScript | JavaScript |
从旧版本升级
7.0 版本前,该模块仅支持单行和可选列号定位。旧版 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);