在使用Biome ↗时,您可能会遇到linter自动将常规导入转换为import type的情况。虽然此功能有助于优化,但有时您希望保留现有的导入语法。本指南介绍了禁用此行为的3种方法。
问题#
Biome有一个useImportType规则,会自动将仅包含类型的导入转换为import type:
// Biome格式化之前
import { Icons } from '../../libs/icons';
// Biome格式化之后
import type { Icons } from '../../libs/icons';typescript这在以下情况下可能会造成困扰:
- 您希望保持常规导入语法的一致性
- 导入也包含运行时值(不仅仅是类型)
- 您正在从ESLint迁移并希望保留代码风格
解决方案#
方法1:全局禁用规则#
最简单的方法是在biome.json文件中禁用useImportType规则:
{
"linter": {
"enabled": true,
"rules": {
"style": {
"useImportType": "off"
}
}
}
}json[!TIP] 修改
biome.json后,记得重启IDE或Biome扩展以使更改生效。
方法2:为特定文件禁用#
如果您只想为特定文件或行禁用它,请使用抑制注释:
// biome-ignore lint/style/useImportType: 保留常规导入语法
import { Icons } from '../../libs/icons';typescript或者将注释放在文件顶部以应用于整个文件:
// biome-ignore-file lint/style/useImportType
import { Icons } from '../../libs/icons';
import { OtherType } from './other';typescript方法3:禁用所有导入组织#
如果Biome在格式化期间移动、排序或重构您的类型导入,您可以完全禁用organizeImports功能:
{
"assist": {
"enabled": true,
"actions": {
"source": {
"organizeImports": {
"enabled": false
}
}
}
}
}json[!WARNING] 这将禁用所有导入组织功能,而不仅仅是类型导入。使用前请仔细考虑。
何时使用每种方法#
| 方法 | 使用时机 | 优点 | 缺点 |
|---|---|---|---|
| 全局 | 团队希望保持常规导入一致 | 适用于整个项目,易于管理 | 失去import type优化好处 |
| 特定文件 | 只有少数文件需要例外 | 灵活,不影响其他代码 | 需要手动添加注释 |
| 禁用organizeImports | 想要完全控制导入组织 | 禁用所有导入自动化 | 失去许多有用功能 |
实际示例#
假设您有一个使用类型导入的Astro组件:
---
import type { Icons } from '../../libs/icons';
interface Props {
name: keyof typeof Icons;
}
---astro禁用useImportType后,您可以这样写:
---
import { Icons } from '../../libs/icons';
interface Props {
name: keyof typeof Icons;
}
---astroBiome不会再自动将其转换回import type。