分享設定
如果您有很多不同的專案,擁有一個可在所有專案中使用的共享設定會很有幫助,而不必為每個專案複製貼上相同的設定。
此頁面說明如何建立、發佈和使用可共享的設定。
建立可共享的設定
可共享的設定只是匯出單個 Prettier 設定檔 的 npm 套件。
在開始之前,請確保您擁有:
- 用於發佈套件的 npmjs.com 帳戶
- 如何建立 Node.js 模組 的基本理解
首先,建立一個新的套件。我們建議使用名稱 @username/prettier-config
建立一個 範圍套件。
一個最小的套件至少應該包含兩個檔案。一個用於套件設定的 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"
}
}
範例儲存庫可在 這裡 找到。
**注意:**您可以使用 peerDependencies
代替 dependencies
。要了解它們的差異,您可以閱讀 Domenic Denicola 關於 peer dependencies 的這篇部落格文章。