設定の共有
多くの異なるプロジェクトがある場合、すべてのプロジェクトで同じ設定をコピー&ペーストするのではなく、それらすべてで使用できる共有設定があると便利です。
このページでは、共有可能な設定の作成、公開、および利用方法について説明します。
共有可能な設定の作成
共有可能な設定は、単一のprettier設定ファイルをエクスポートするnpmパッケージにすぎません。
始める前に、以下を確認してください。
- パッケージを公開するためのnpmjs.comのアカウント
- Node.jsモジュールを作成する方法に関する基本的な理解
まず、新しいパッケージを作成します。 @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
yarn add --dev @username/prettier-config
pnpm add --save-dev @username/prettier-config
bun add --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";
/**
* @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.json
のdependencies
でそれらのプラグインを宣言する必要があります
// 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によるピア依存関係に関するこのブログ投稿を読むことができます