白筱汐

想都是问题,做都是答案

0%

前端工具库-biome

前端工具库 - biome

biome 是web项目的工具链,帮助我们完成代码格式化与规则校验。类似 prettier 与 eslint 的功能,不过它的速度更快,因为 biome 基于 rust 语言构建。详情请查看 biome官网 或者 github

安装

需要 node 版本 14.18+。

1
npm install --save-dev --save-exact @biomejs/biome

使用

运行以下命令进行 初始化。

1
npx @biomejs/biome init

在项目的根目录会生成 biome.json 文件,也就是项目的配置文件。

1
2
3
4
5
6
7
8
9
10
11
12
{
"$schema": "https://biomejs.dev/schemas/1.4.0/schema.json",
"organizeImports": {
"enabled": false
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
}
}
}

简单介绍一下配置的含义:

  • organizeImports: enabled 启用 import 语句排序优化。
  • linter: enabled 启用规则校验, recommended 使用推荐的规则。

格式化文件

1
npx @biomejs/biome format --write ./src

校验文件

1
npx @biomejs/biome lint --write ./src

运行format, lint等,并应用安全建议(不会修改代码)

1
npx @biomejs/biome check --write ./src

运行format, lint等,并应用建议修改代码

1
npx @biomejs/biome check --write-unsafe ./src

自定义校验规则

下面配置出前端项目基础的 prettier 、 lint 规则,应用于 biome

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
{
"$schema": "https://biomejs.dev/schemas/1.8.0/schema.json",
"organizeImports": {
"enabled": true
},
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": true
},
"formatter": {
"enabled": true,
"formatWithErrors": false,
"ignore": [],
"indentStyle": "tab",
"indentWidth": 2,
"lineWidth": 120
},
"javascript": {
"formatter": {
"enabled": true,
"semicolons": "always",
"quoteStyle": "single",
"jsxQuoteStyle": "double",
"trailingCommas": "all"
}
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
}
}
}

可以看到 biome 的配置规则与 prettier 的区别,部分规则配置到了 javascript 下。 关于 json 的配置这里就不说明了,具体请查看官网的 configuration 目录。

插件安装

在 vscode 中搜索 “Biome” 并安装插件。

biome

使用案例

在项目的根目录 package.json 新增一条 script, 如下所示

1
2
3
4
5
6
7
{
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"biome-fix": "npx @biomejs/biome check --write--unsafe index.js"
}
}

新建一个 index.js 文件,内容如下,你可以随意写一些内容,主要是为了触发校验规则。

原代码

在项目的根目录进行命令 npm run biome-fix,结果如下:

修复后的代码

由于脚本使用了 check 命令,会同时使用 format 和 lint,–apply-unsafe 会应用建议并修改代码。

总结

biome 帮助我们简化了 prettier 与 eslint 的配置,并且它拥有极快的速度。对于大型项目还支持项目配置的分解和继承,类似 webpack 的 merge config。但是目前还没有发现对于前端框架的更好的支持,希望以后可以加入对于 vue 、react 的语法进行校验优化。