メインコンテンツへスキップ

設定の共有

非公式ベータ版翻訳

このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →

複数の異なるプロジェクトをお持ちの場合、各プロジェクトごとに同じ設定をコピーする代わりに、すべてのプロジェクトで使用できる共有設定があると便利です。

このページでは、共有設定の作成・公開・使用方法について説明します。

共有設定の作成

共有設定は単なるnpmパッケージであり、単一のPrettier設定ファイルをエクスポートします。

開始前に以下を確認してください:

まず新しいパッケージを作成します。名前は@username/prettier-configのようなスコープ付きパッケージを作成することを推奨します。

最小限のパッケージには少なくとも2つのファイルが必要です。パッケージ設定用のpackage.jsonと、共有Prettier設定オブジェクトを保持するindex.jsです:

prettier-config/
├── index.js
└── package.json

package.jsonの例:

{
"name": "@username/prettier-config",
"version": "1.0.0",
"description": "My personal Prettier config",
"type": "module",
"exports": "./index.js",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"peerDependencies": {
"prettier": ">=3.0.0"
}
}

index.jsには共有設定を記述します。このファイルは通常のPrettier設定と同じ構文・オプションで設定をエクスポートします:

const config = {
trailingComma: "es5",
tabWidth: 4,
singleQuote: true,
};

export default config;

共有設定のリポジトリ例はこちらで確認できます。

共有設定の公開

準備が整ったら、パッケージをnpmに公開できます:

npm publish

共有設定の使用

まず公開した設定をインストールする必要があります。例:

npm install --save-dev @username/prettier-config

その後、package.jsonで参照できます:

{
"name": "my-cool-library",
"version": "1.0.0",
"prettier": "@username/prettier-config"
}

package.jsonを使用したくない場合は、.prettierrcなどサポートされている拡張子で文字列をエクスポートできます:

"@company/prettier-config"

共有設定の拡張

共有設定の一部プロパティを上書きして設定を_拡張_するには、.prettierrc.mjsファイルで設定ファイルをインポートし、変更内容をエクスポートします。例:

import usernamePrettierConfig from "@username/prettier-config";

/**
* @see https://prettier.io/docs/configuration
* @type {import("prettier").Config}
*/
const config = {
...usernamePrettierConfig,
semi: false,
};

export default config;

その他の例

共有設定での型注釈の使用

jsdoc型注釈を使用すると、共有設定で型安全性とオートコンプリートを実現できます:

/**
* @type {import("prettier").Config}
*/
const config = {
trailingComma: "es5",
tabWidth: 4,
semi: false,
singleQuote: true,
};

export default config;

これを機能させるには、プロジェクトにprettierをインストールする必要があります。

その後、package.jsonファイルは次のようになります:

{
"name": "@username/prettier-config",
"version": "1.0.0",
"description": "My personal Prettier config",
"type": "module",
"exports": "./index.js",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"peerDependencies": {
"prettier": ">=3.0.0"
},
+ "devDependencies": {
+ "prettier": "^3.3.3"
+ }
}

共有設定へのプラグイン組み込み

共有設定でプラグインを使用する場合、設定ファイルのplugin配列とpackage.jsondependenciesにそれらを宣言する必要があります:

// index.js
const config = {
singleQuote: true,
plugins: ["prettier-plugin-xml"],
};

export default config;
// package.json
{
"name": "@username/prettier-config",
"version": "1.0.0",
"description": "My personal Prettier config",
"type": "module",
"exports": "./index.js",
"license": "MIT",
"publishConfig": {
"access": "public"
},
+ "dependencies": {
+ "prettier-plugin-xml": "3.4.1"
+ },
"peerDependencies": {
"prettier": ">=3.0.0"
}
}

実装例はこちらで確認できます。

注: dependenciesの代わりにpeerDependenciesを使用できます。違いについてはDomenic Denicolaのpeer dependenciesに関するブログ記事を参照してください。