跳至主内容区

共享配置方案

非官方测试版翻译

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

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

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

创建共享配置

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

开始前请确保已具备:

首先创建新包,建议使用作用域包命名格式 @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"
}
}

index.js 用于存放共享配置,该文件只需导出与 标准 Prettier 配置 语法相同的配置对象:

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 中引用:

{
"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";

/**
* @see https://prettier.io/docs/configuration
* @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"
}
}

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

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