共享配置方案
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
当您管理多个不同项目时,使用共享配置可以避免在每个项目中重复复制粘贴相同的配置。
本文将指导您如何创建、发布和使用可共享的配置方案。
创建共享配置
共享配置本质上就是导出了单个 Prettier 配置文件 的 npm 包。
开始前请确保已具备:
-
npmjs.com 账号用于发布包
-
创建 Node.js 模块的基础知识
首先创建新包,建议使用作用域包命名格式 @username/prettier-config 创建 scoped package。
最小化包应包含两个文件:配置包信息的 package.json 和存储共享配置对象的 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;
可参考此处的共享配置示例仓库:https://github.com/azz/prettier-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%"
}
}
注意: 可使用 peerDependencies 替代 dependencies,差异说明详见 Domenic Denicola 的博客文章:关于 peer dependencies 的解析