跳至主内容区

共享配置方案

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

当您管理多个不同项目时,使用共享配置可以避免在每个项目中重复复制粘贴相同的配置。

本文将指导您如何创建、发布和使用可共享的配置方案。

创建共享配置

共享配置本质上就是导出了单个 Prettier 配置文件npm 包

开始前请确保已具备:

首先创建新包,建议使用作用域包命名格式 @username/prettier-config 创建 scoped package

最小化包应包含两个文件:配置包信息的 package.json 和存储共享配置对象的 index.js

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

示例 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 配置 语法相同的配置对象:

index.js
/**
* @see https://prettier.io/docs/configuration
* @type {import("prettier").Config}
*/
const config = {
trailingComma: "es5",
tabWidth: 4,
singleQuote: true,
};

export default config;

可参考此处的共享配置示例仓库:https://github.com/azz/prettier-config

发布共享配置

准备就绪后,可 将包发布至 npm

npm publish

使用共享配置

首先安装已发布的配置,例如:

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

然后在 package.json 中引用:

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

若不使用 package.json,可通过支持的文件扩展名导出字符串,例如 .prettierrc

.prettierrc
"@company/prettier-config"

扩展共享配置

若要_扩展_配置以覆盖共享配置中的某些属性,可在 prettier.config.mjs 文件中导入该文件并导出修改后的配置,例如:

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

index.js
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;
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-oxc": "0.1.2"
+ },
"peerDependencies": {
"prettier": ">=3.0.0"
},
"devDependencies": {
"prettier": "%PRETTIER_VERSION%"
}
}

示例仓库参见:https://github.com/kachkaev/routine-npm-packages/tree/bc3e658f88c0b41beb118c7a1b9b91ec647f8478/packages/prettier-config

注意: 可使用 peerDependencies 替代 dependencies,差异说明详见 Domenic Denicola 的博客文章:关于 peer dependencies 的解析