設定の共有
このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →
複数の異なるプロジェクトをお持ちの場合、各プロジェクトごとに同じ設定をコピーする代わりに、すべてのプロジェクトで使用できる共有設定があると便利です。
このページでは、共有設定の作成・公開・使用方法について説明します。
共有設定の作成
共有設定は単なるnpmパッケージであり、単一のPrettier設定ファイルをエクスポートします。
開始前に以下を確認してください:
-
パッケージ公開用の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"
},
"devDependencies": {
"prettier": "%PRETTIER_VERSION%"
}
}
index.jsには共有設定を記述します。このファイルは通常のPrettier設定と同じ構文・オプションで設定をエクスポートします:
/**
* @see https://prettier.io/docs/configuration
* @type {import("prettier").Config}
*/
const config = {
trailingComma: "es5",
tabWidth: 4,
singleQuote: true,
};
export default config;
共有設定のリポジトリ例はこちらで確認できます。
共有設定の公開
準備が整ったら、パッケージをnpmに公開できます:
npm publish
共有設定の使用
まず公開した設定をインストールする必要があります。例:
- npm
- yarn
- pnpm
- bun
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"
共有設定の拡張
共有設定の一部のプロパティを上書きして設定を_拡張_するには、prettier.config.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;
その他の例
共有設定へのプラグイン組み込み
共有設定でプラグインを使用する場合、設定ファイルのplugin配列とpackage.jsonのdependenciesにそれらを宣言する必要があります:
import * as prettierPluginOxc from "@prettier/plugin-oxc";
/**
* @see https://prettier.io/docs/configuration
* @type {import("prettier").Config}
*/
const config = {
singleQuote: true,
plugins: [prettierPluginOxc],
};
export default config;
{
"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-oxc": "0.1.2"
+ },
"peerDependencies": {
"prettier": ">=3.0.0"
},
"devDependencies": {
"prettier": "%PRETTIER_VERSION%"
}
}
実装例はこちらで確認できます。
注: dependenciesの代わりにpeerDependenciesを使用できます。違いについてはDomenic Denicolaのpeer dependenciesに関するブログ記事を参照してください。