Taro项目中使用f2elint

发布时间 2023-04-18 14:55:26作者: ZerlinM

一、f2elint全局安装

yarn安装

yarn add global f2elint

或者
npm安装

npm i f2elint -g

查看是否安装成功

npx f2elint -h

二、f2elint初始化

在项目根目录下初始化

npx f2elint init

1.会提示选择项目的语言和框架类型,此处我选择 react + ts

2.选择是否需要样式的检查,此处我选择 Y

3.是否检查markdown 此处我选择 n

4.是否用Prettier插件格式化代码 此处我选择 Y

5.检查冲突,确认是否继续,此处我选择 Y

6.安装依赖

7.初始化完成

三、使用

package.json中会多出2条脚本(第三条为自行添加,可对要提交的代码进行分析)

"f2elint-scan": "npx f2elint scan",
"f2elint-fix": "npx f2elint fix",
"f2elint-commit-file-scan": "npx f2elint commit-file-scan"

这时就可以使用以下命令 查看代码分析

yarn f2elint-scan

注意:
vscode用户需要安装三个插件

  • ESLint

  • Stylelint

  • Prettier - Code formatter

此时即可开心的使用eslint了~~~
如果使用命令时有报错之类的,可以先尝试删除node_modules重新安装,未解决的话可自行百度具体报错~~

四、设置eslint规则

比如不希望出现 已声明但未使用的报错提示,则可设置.eslintrc.js如下
'@typescript-eslint/no-unused-vars': 'off'
比如希望空格2个,则可设置.eslintrc.js如下
'@typescript-eslint/indent': ['error', 2, { SwitchCase: 1 }],

rules: {
    '@typescript-eslint/no-unused-vars': 'off',
    '@typescript-eslint/indent': ['error', 2, { SwitchCase: 1 }],
},

f2lint中使用了commitlint校验提交代码时的备注信息,格式为 [subject]:
但是我们不想使用这种信息格式,可配置文件 .commitlint.config.js

module.exports = {
  extends: ['ali'],
  rules: {
    'subject-empty': [0],
    'type-empty': [0],
  },
};

表示type可为空,subject可为空

五、部分ts校验提示 找不到模块 xxx 或其响应的类型声明

taro创建项目时,会自动创建一个文件夹types,其中有个文件为 global.d.ts

但是我们需要在根目录中的 tsconfig.json中添加该文件,如下

配置好之后保存,即可发现报错提示消失了。

六、在taro启动项目前校验

由于项目是多人开发,期望统一项目风格,所以在项目中添加了如下校验。
对修改后待提交的文件进行校验
新建bin文件夹,文件夹中新建文件 scan-by-file.js

const f2elint = require('f2elint');
const cwd = process.cwd();
const fs = require('fs');
const failureReturn = function () {
  process.exit(1);
};

try {
  const result = fs.readFileSync(cwd + '/bin/files', { encoding: 'utf-8' });
  fs.rmSync(cwd + '/bin/files');
  const fileList = result.trim().split('\n');

  f2elint
    .scan({
      cwd,
      files: fileList,
      // 只显示错误信息
      quiet: true,
    })
    .then(
      (res) => {
        if (res.errorCount) {
          console.error(new Error('有' + res.errorCount + '条代码风格错误,请修改后重新提交!'));
          failureReturn();
        }
      },
      (err) => {
        console.log('f2elint scan error', err);
        failureReturn();
      },
    );
} catch (err) {
  console.log('try..catch error', err);
  failureReturn();
}

package.json中添加

"check-all-uncommited-files": "git diff --pretty=format: --name-only > ./bin/files && node ./bin/scan-by-file.js",
"dev:weapp": "yarn check-all-uncommited-files && npm run build:weapp -- --watch",

此时执行启动命令时,则会先校验文件成功后 在会启动程序

yarn dev:weapp