prettier继承

不支持extends

prettier配置并不支持 extends 关键字,但是我们可以手动合并,比方说我们下载了一个配置包 @repo/config-prettier,我们可以如下继承到自己项目中

// prettier.config.js
const configPrettier = require('@repo/config-prettier');

module.exports =  {
  ...configPrettier,
};

配置包使用了三方库

// @repo/config-prettier的 index.js
export default {
  tabWidth: 2, // 缩进2个空格
  useTabs: false, // 缩进单位是否使用tab替代空格
  semi: true, // 句尾添加分号
  singleQuote: true, // 使用单引号代替双引号
  printWidth: 10000,
  plugins: ['./node_modules/prettier-plugin-sort-imports/dist/index.js'],
  sortingMethod: 'lineLength',
  sortingOrder: 'ascending',
};
// @repo/config-prettier的 package.json
{
  "name": "@repo/config-prettier",
  "version": "0.0.1",
  "description": "Prettier configuration for the monorepo",
  "main": "base.js",
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "prettier-plugin-sort-imports": "^1.8.7"
  }
}

使用者需要安装吗?

那我自己的项目还需要安装prettier-plugin-sort-imports 吗?

是的,你还是需要在你的项目中单独安装 prettier-plugin-sort-imports,即使在 @repo/config-prettier 中引用了该插件。
解释原因:
• Prettier 插件的加载方式:Prettier 插件(如 prettier-plugin-sort-imports)必须被安装在使用该配置的项目中,即使你在 @repo/config-prettier 中通过相对路径引用了插件,Prettier 还是会寻找项目中 node_modules 中的插件,而不是通过依赖关系的路径自动加载。
• plugins 字段:在 Prettier 配置中使用 plugins 指定插件时,Prettier 会依赖当前项目的 node_modules 中的插件。所以,即使你在 @repo/config-prettier 配置中引用了插件路径,仍然需要在项目中安装插件。

解决办法

你不能要求每个使用者,都如你所愿“乖乖安装 prettier-plugin-sort-imports”,所以你可以这么做:将配置包@repo/config-prettier 的 package.json 改为

// @repo/config-prettier的 package.json
{
  "name": "@repo/config-prettier",
  // ...
  "peerDependencies": {
    "prettier-plugin-sort-imports": "^1.8.7"
  }
}

这是因为,用户在安装某个依赖的时候会自动安装它 peerDependencies 里的包

找不到 plugin 的 path

@repo/config-prettier 是我们封装的一个常用prettier的 npm 包,在新项目中我们这么使用

// prettier.config.js
const configPrettier = require('@repo/config-prettier');

module.exports =  {
  ...configPrettier,
};

但这就会出现一个问题:
在@repo/config-prettier 的封装中,针对插件prettier-plugin-sort-imports的引用, 虽然写了相对路径 ['./node_modules/prettier-plugin-sort-imports/dist/index.js'
但是在当前项目中进行prettier时,因prettier运行是在作用域是在跟目录,这会导致在使用者的 node_module里无法找到这个包,既

your project
  |--node_modules
      |-- @repo/config-prettier
            | --node_modules
                  |--prettier-plugin-sort-imports

有两种办法解决,要么在使用的地方将其依赖提升,或者按照推荐的写法封装: 通过 require('xxx') 反向获取它当前的绝对路径

// @repo/config-prettier/index.js
const pluginPath = require.resolve('prettier-plugin-sort-imports');

module.exports = {
  plugins: [pluginPath],
  sortingMethod: "lineLength",
  sortingOrder: "ascending",
};
posted @ 2025-04-29 14:02  丁少华  阅读(38)  评论(0)    收藏  举报