👻

BiomeのCLIではなくAPIを使ってコードをフォーマットする

に公開

BiomeのコードフォーマッターをJavaScriptのAPIから使いたいと思う事はありませんか? 私はありましたので、この記事ではその方法を書きます。

biomeのCLIを使う場合は、 @biomejs/biome パッケージをインストールしますが、JavaScriptのAPIを利用する場合は別のパッケージをインストールします。ここではNode.js環境下で動かす事を前提として、@biomejs/wasm-nodejsと@biomejs/js-apiをインストールします。

$ npm add @biomejs/wasm-nodejs @biomejs/js-api

以下こんな感じでAPIを呼び出してフォーマットできました。

import { Biome } from "@biomejs/js-api/nodejs";

export function formatCode(code: string): string {
  const biome = new Biome();
  try {
    const cwd = (typeof process !== "undefined" && typeof process.cwd === "function") ? process.cwd() : "/";
    const { projectKey } = biome.openProject(cwd);

    biome.applyConfiguration(projectKey, {
      formatter: {
        formatWithErrors: true,
        indentStyle: "space",
        indentWidth: 2,
        enabled: true,
      },
    });

    const filePath = `${cwd.replace(/\\+$/, "")}/generated.ts`;
    const result = biome.formatContent(projectKey, code, { filePath });
    if (result.diagnostics.length > 0) {
      throw new Error(`Formatting failed: ${result.diagnostics.map(d => d.description).join(", ")}`);
    }
    return result.content;
  } finally {
    biome.shutdown();
  }
}

おしまい。

Discussion