【前言】本文涉及项目工程化问题,配置eslint和pretrtier时发现问题,因此记录在这,防止各位小伙伴踩坑,感兴趣的小伙伴可以耐心阅读下去,我会尽可能讲的有趣一些,如有问题也可以一起交流学习,本人React工作经验很少,只有简单服务器搭建基础,目前也在不断学习中,若下面的内容有错误,请各位大佬指正,理性讨论,谢谢☃️
【备注】本文的实现均用 React 实现,各位小伙伴可以采用其他的实现,vue或者纯html都可以,只是方便使用就好,根据自己所需要的业务场景进行更换即可。
【导读】
- 问题描述
- 问题排查
- 解决问题
- 其他问题
问题描述
husky 执行 npm run lint (其实就是执行 eslint . --max-warnings=0)的情况下发现 prettier 与 eslint 校验存在问题
Oops! Something went wrong! :(
ESLint: 7.20.0
TypeError: Error while loading rule 'prettier/prettier': context.getPhysicalFilename is not a function
问题排查
以个人经验来说,看到报错大概率就会想到eslint配置项出现问题(没有经验就直接百度哈),一般都是eslint导入extends时出的问题,也就是eslint的扩展有问题,最经常出问题的就是版本不兼容。
所以立马打开.eslintrc文件查看代码,代码如下
{
"extends": [
"taro/react",
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended"
],
"rules": {
"react/jsx-uses-react": "off",
"react/react-in-jsx-scope": "off",
"react/jsx-indent-props": ["warn", 4],
"jsx-quotes": ["error", "prefer-double"],
"semi": ["warn", "always"],
"prefer-const": "warn",
"@typescript-eslint/indent": ["warn", 4],
"import/no-commonjs": "off",
"space-before-function-paren": "off",
"eol-last": "off",
"@typescript-eslint/no-explicit-any": "off",
"no-case-declarations": "off",
"no-empty": "off",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-empty-function": "off",
"react-hooks/exhaustive-deps": "off",
"@typescript-eslint/explicit-module-boundary-types": "off"
}
}
各位小伙伴发现什么了吗,没错。代码确实有在extends里存在prettier相关扩展,先测试一下,注释掉"plugin:prettier/recommended",再执行npm run lint,可以正常校验了。
其实这个扩展主要用于解决Expected indentation of 36 spaces but found 38.eslint[@typescript-eslint/indent] 缩进冲突问题,让eslint与prettier出现冲突时选择prettier的方式进行代码格式化。
定位到问题后,马上开始查阅官方文档,查了一下github上eslint-plugin-prettier的issue,嘿,还真让我找到了一模一样的问题点击跳转,英文不好,看了半天,大意就是react-scripts与eslint版本的问题。
查看了自己的版本,版本如下:
"eslint": "^7.20.0",
"eslint-plugin-prettier": "^4.2.1",
"prettier": "^1.19.1",
解决问题
根据issue提出的问题的大神给出的解决方案就是yarn upgrade -R eslint(原文为yarn up -R eslint,其实也就是更新版本,尝试了一下我发现会遇到命令执行不了的问题,应该是版本不一样吧,Small addition: if you're using yarn v2+ the command has been renamed to the following yarn up -R eslint. 其实就是v2+版本已经更新为yarn up xxx,自己区分一下版本即可)去更新深层的eslint版本,让嵌套的依赖得到更新,以正常使用eslint-plugin-prettier。
执行
npm i eslint@7.32.0 --force
最后选择了升级eslint版本,升级为版本如下
"eslint": "^7.32.0",
"eslint-plugin-prettier": "^4.2.1",
"prettier": "^1.19.1",
至此,问题解决。
在这之后协同开发的各位小伙伴记得把你自己的yarn.lock上传,在issue中有提到react-scripts relies on eslint@^7.11.0 according to your own yarn.lock,其实就是 react-scripts在eslint7.11.0以上的版本会依赖于yarn.lock内的版本。
其他问题
相信很多小伙伴想问npm update能不能等价于yarn up -R eslint的命令,我这边执行不了这个命令,估计是深层依赖嵌套产生了版本问题,npm一直提醒我去使用--force, or --legacy-peer-deps参数,其实是不太好的,但最终还是妥协了哈哈哈。
使用npm的小伙伴也可以直接尝试yarn upgrade -R eslint或yarn up -R eslint看看,你就会发现有些依赖不行了哈哈哈哈哈哈哈。。