@babel/code-frame
安裝
- npm
- Yarn
- pnpm
npm install --save-dev @babel/code-frame
yarn add --dev @babel/code-frame
pnpm add --save-dev @babel/code-frame
用法
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
hash。
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
布林值
,預設為 false
。
切換語法,將程式碼標記為終端的 JavaScript。
linesAbove
數字
,預設為 2
。
調整顯示在錯誤上方行數。
linesBelow
數字
,預設為 3
。
調整顯示在錯誤下方行數。
forceColor
布林值
,預設為 false
。
啟用此選項可強制將程式碼語法標記為 JavaScript(非終端);覆寫 highlightCode
。
message
字串
,否則為空值
傳遞一個字串,以在程式碼中標記位置旁邊內嵌顯示(如果可能)。如果無法內嵌定位,它將置於程式碼框架上方。
1 | class Foo {
> 2 | constructor()
| ^ Missing {
3 | };
從先前版本升級
在版本 7 之前,此模組公開的唯一 API 是用於單行和選用欄位指標。舊 API 現在會記錄不建議使用的警告。
新的 API 會採用一個類似於 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);