Import文のソート
Biomeは、import文を自然順に従ってソートします。
この機能はデフォルトで有効ですが、以下のように設定を通じてオプトアウトすることができます。
{ "organizeImports": { "enabled": false }}
Import文がどのようにソートされるか
Section titled Import文がどのようにソートされるかimport文は、“距離” によってソートされます。ユーザーから “遠い” モジュールが上に配置され、ユーザーに “近い” モジュールが下に配置されます。
bun:
プロトコルを介してインポートされたモジュール。これはBunによって実行されるコードを書く場合に適用されます。node:
プロトコルを使用して明示的にインポートされるNode.jsの組み込みモジュールおよびassert
などの一般的なNodeビルトイン。npm:
プロトコルを介してインポートされたモジュール。これはDenoで実行されるコードを書く場合に適用されます。- URLを介してインポートされたモジュール。
- ライブラリからインポートされたモジュール。
- 絶対インポート (absolute import) を使用してインポートされたモジュール。
#
の接頭辞が付いた名前からインポートされたモジュール。これは、Nodeのサブパスインポートを使用する場合に適用されます。- 相対インポート (relative import) を使用してインポートされたモジュール。
- 前述の基準で識別できなかったモジュール。
例えば、次のコードが与えられた場合、
import uncle from "../uncle";import sibling from "./sibling";import express from "npm:express";import imageUrl from "url:./image.png";import assert from "node:assert";import aunt from "../aunt";import { VERSION } from "https://deno.land/std/version.ts";import { mock, test } from "node:test";import { expect } from "bun:test";import { internal } from "#internal";import { secret } from "/absolute/path";import React from "react";
次のようにソートされます。
import { expect } from "bun:test";import assert from "node:assert";import { mock, test } from "node:test";import express from "npm:express";import { VERSION } from "https://deno.land/std/version.ts";import React from "react";import { secret } from "/absolute/path";import { internal } from "#internal";import aunt from "../aunt";import uncle from "../uncle";import sibling from "./sibling";import imageUrl from "url:./image.png";
ソートを適用する方法は、CLIを使用した場合またはVS Code拡張機能を使用した場合の2つあります。
グループインポート
Section titled グループインポート主にフロントエンドのプロジェクトで作業する場合やCSSファイルをインポートする際には、特定の順序でimport文を宣言することは一般的です。
import "../styles/reset.css";import "../styles/layout.css";import { Grid } from "../components/Grid.jsx";
他の一般的なケースは、polyfillやshimファイルをインポートすることです。これらはファイルの先頭に配置する必要があります。
import "../polyfills/array/flatMap";import { functionThatUsesFlatMap } from "./utils.js";
こういったケースでは、Biomeがimport文をすべてソートすることによりアプリケーションの従来の挙動を壊す可能性があります。
これを回避するためにはimport文の”グループ”を作成します。改行を追加することでグループに区切ることができます。
これによりBiomeは、ソートの対象をグループに属するimport文のみに制限します。
// group 1, only these two files will be sortedimport "../styles/reset.css";import "../styles/layout.css";
// group 2, only this one is sortedimport { Grid } from "../components/Grid.jsx";
// group 1, the polyfill/shimimport "../polyfills/array/flatMap";
// group 2, the files tha require the polyfill/shimimport { functionThatUsesFlatMap } from "./utils.js";
CLIを使用した場合
Section titled CLIを使用した場合オプション--write
を指定して、check
コマンドを実行します。
biome check --write ./path/to/src
VS Code拡張機能を使用した場合
Section titled VS Code拡張機能を使用した場合BiomeのVS Code拡張機能は、Organize Imports コードアクションによるimport文のソートをサポートしています。 このアクションはデフォルトで ⇧+Alt+O キーボードショートカットを使用して実行するか、 コマンドパレット (Ctrl/⌘+⇧+P) から Organize Imports を選択してアクセスできます。
ファイル保存時に自動で実行したい場合は、エディタの設定に以下を追加することで実現できます。
{ "editor.codeActionsOnSave": { "source.organizeImports.biome": "explicit" }}