eslint+husky+perttier+commitizen+typedoc配置

121 阅读5分钟

eslint-webpack-plugin

yarn add eslint-webpack-plugin eslint --save-dev

webpack.config.js

const path = require("path");
const ESLintPlugin = require('eslint-webpack-plugin');

const currPath = process.cwd();

module.exports = {
  mode: "development",
  entry: './src/index.js',
  output: {
    filename: '[name].[hash:8].js',
    path: path.resolve(currPath, 'dist'),
  },
  plugins: [
    ESLintPlugin({
      // exclude: '',
	  lintDirtyModulesOnly: true, // 只对修改的文件进行检查
    }),
  ],
}

eslint 配置文件建议放在项目根目录

  • .eslintrc
  • .eslintrc.js
  • .eslintrc.json
  • package.json 中的eslintConfig
level
off或0关闭
warn或1警告级别的错误(不会导致程序退出)
error或2错误级别的错误(当被触发的时候,程序会终止,编译会暂停)

vscode中可以安装ESLint配合使用

module.exports = {
  root: true, //停止在父级目录中寻找
  parserOptions: {
    sourceType: "module",
  },
  env: {
    browser: true,
    node: true,
    es6: true,
  },
  // extends: ["prettier", "plugin:prettier/recommended"],
  extends: [
    "react-app",
    "react-app/jest",
    "eslint:recommended", //https://eslint.bootcss.com/docs/rules/
  ],
  rules: {
    "no-control-regex": 0,
    // 关闭hooks依赖检测
    "react-hooks/exhaustive-deps": 0,
    // 关闭不许使用默认导出
    "import/no-anonymous-default-export": 0,
    "no-debugger": "off", // 关闭 debugger 报错提示
    "no-undef": 0, //关闭$
    "no-unused-expressions": 0, //关闭无用表达式
  },
};

root - 限定配置文件的使用范围 parser - 指定eslint的解析器 parserOptions - 设置解析器选项 extends - 指定eslint规范 plugins - 引用第三方的插件 env - 指定代码运行的宿主环境 rules - 启用额外的规则或覆盖默认的规则 globals - 声明在代码中的自定义全局变量

package.json 中添加

"script": {
	"lint": "eslint --fix ./ --ext .ts --ext   .js",
}

prettier

安装

npm install --save-dev --save-exact prettier

根目录创建配置文件 .prettierrc.js

module.exports ={
	printWidth: 80, //单行长度
    tabWidth: 2, //缩进长度
    useTabs: false, //使用空格代替tab缩进
    semi: true, //句末使用分号
    singleQuote: true, //使用单引号
    quoteProps: 'as-needed', //仅在必需时为对象的key添加引号
    jsxSingleQuote: true, // jsx中使用单引号
    trailingComma: 'all', //多行时尽可能打印尾随逗号
    bracketSpacing: true, //在对象前后添加空格-eg: { foo: bar }
    jsxBracketSameLine: true, //多属性html标签的‘>’折行放置
    arrowParens: 'always', //单参数箭头函数参数周围使用圆括号-eg: (x) => x
    requirePragma: false, //无需顶部注释即可格式化
    insertPragma: false, //在已被preitter格式化的文件顶部加上标注
    proseWrap: 'preserve', //不知道怎么翻译
    htmlWhitespaceSensitivity: 'ignore', //对HTML全局空白不敏感
    vueIndentScriptAndStyle: false, //不对vue中的script及style标签缩进
    endOfLine: 'lf', //结束行形式
    embeddedLanguageFormatting: 'auto', //对引用代码进行格式化
}

package.json 中配置命令

script: {
	"prettier": "prettier --config .prettierrc.js --write ./**/*.{js,ts,scss,css,json}",
}

husky

安装husky

npm install husky --save-dev  
or 
yarn add husky -D

package.json

"scripts": {
	 "prepare": "husky install"
 },

yarn prepare 的作用是 在其他用户安装项目依赖时会自动执行husky install; 配置完成后,在项目中执行npm prepare(也就是执行了husky install); 执行完成后,会在项目根目录生成一个.husky文件夹

添加pre-commit钩子

在项目根目录执行
npx husky add .husky/pre-commit 'npm run lint-staged';

执行命令添加commit-msg钩子

npx husky add .husky/commit-msg "yarn commitlint"

在项目根目录创建commitlint.config.js

module.exports = {
    parserPreset: 'conventional-changelog-conventionalcommits',
    // 继承的规则
    extends: ["@commitlint/config-conventional"],
    rules: {
      'body-leading-blank': [1, 'always'],
      'body-max-line-length': [2, 'always', 100],
      'footer-leading-blank': [1, 'always'],
      'footer-max-line-length': [2, 'always', 100],
      'header-max-length': [2, 'always', 100],
      'subject-case': [
        2,
        'never',
        ['sentence-case', 'start-case', 'pascal-case', 'upper-case']
      ],
      'subject-empty': [2, 'never'],
      'subject-full-stop': [2, 'never', '.'],
      'type-case': [2, 'always', 'lower-case'],
      'type-empty': [2, 'never'],
      'type-enum': [
        2,
        'always',
        [
          'build', // 编译相关的修改,例如发布版本、对项目构建或者依赖的改动
          'feat', // 新功能
          'fix', // 修补bug
          'docs', // 文档修改
          'style', // 代码格式修改, 注意不是 css 修改
          'refactor', // 重构
          'perf', // 优化相关,比如提升性能、体验
          'test', // 测试用例修改
          'revert', // 代码回滚
          'ci', // 持续集成修改
          'config', // 配置修改
          'chore' // 其他改动
        ]
      ]
    },
    prompt: {
      questions: {
        type: {
          description: "Select the type of change that you're committing",
          enum: {
            feat: {
              description: 'A new feature',
              title: 'Features',
              emoji: '✨'
            },
            fix: {
              description: 'A bug fix',
              title: 'Bug Fixes',
              emoji: '🐛'
            },
            docs: {
              description: 'Documentation only changes',
              title: 'Documentation',
              emoji: '📚'
            },
            style: {
              description:
                'Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)',
              title: 'Styles',
              emoji: '💎'
            },
            refactor: {
              description:
                'A code change that neither fixes a bug nor adds a feature',
              title: 'Code Refactoring',
              emoji: '📦'
            },
            perf: {
              description: 'A code change that improves performance',
              title: 'Performance Improvements',
              emoji: '🚀'
            },
            test: {
              description: 'Adding missing tests or correcting existing tests',
              title: 'Tests',
              emoji: '🚨'
            },
            build: {
              description:
                'Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)',
              title: 'Builds',
              emoji: '🛠'
            },
            ci: {
              description:
                'Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)',
              title: 'Continuous Integrations',
              emoji: '⚙️'
            },
            chore: {
              description: "Other changes that don't modify src or test files",
              title: 'Chores',
              emoji: '♻️'
            },
            revert: {
              description: 'Reverts a previous commit',
              title: 'Reverts',
              emoji: '🗑'
            }
          }
        },
        scope: {
          description:
            'What is the scope of this change (e.g. component or file name)'
        },
        subject: {
          description: 'Write a short, imperative tense description of the change'
        },
        body: {
          description: 'Provide a longer description of the change'
        },
        isBreaking: {
          description: 'Are there any breaking changes?'
        },
        breakingBody: {
          description:
            'A BREAKING CHANGE commit requires a body. Please enter a longer description of the commit itself'
        },
        breaking: {
          description: 'Describe the breaking changes'
        },
        isIssueAffected: {
          description: 'Does this change affect any open issues?'
        },
        issuesBody: {
          description:
            'If issues are closed, the commit requires a body. Please enter a longer description of the commit itself'
        },
        issues: {
          description: 'Add issue references (e.g. "fix #123", "re #123".)'
        }
      }
    }
  };

安装lint-staged

npm install lint-staged --save-dev
or
yarn add lint-staged -D

package.json

 "scripts": {
	 "lint-staged": "lint-staged",
	 "prepare": "husky install"
 },
 "lint-staged": {
 "*.{js,ts,vue,jsx,tsx}": [
		 "prettier --write",
		 "eslint --cache --fix",
		 "git add"
	 ]
 },

注意:这里使用prettier和eslint格式化代码,需要在项目中先安装对应依赖和配置

commitizen

install

yarn global add commitizen

package.json中自动加入了如下命令

"config": {
    "commitizen": {
      "path": "./node_modules/cz-conventional-changelog"
    }
  }

执行命令 git cz,按照提示完成git commit即可

{
  "include": ["src/"],
  "exclude": ["node_modules/**"],
  "compilerOptions": {
    "target": "ES2019",
    "module": "ESNext",
    "moduleResolution": "node",
    // "strict": true,
    // "esModuleInterop": true,
    "noImplicitOverride": true, //开启此选项保证子类重写基类的方法时, 必须在方法前加上override关键词No quick fixes available
    "noUnusedLocals": true,
    "resolveJsonModule": true,
    "useUnknownInCatchVariables": false, //将catch语法块中的err变量当做unknown来处理, 不开启此选项时, err变量是被当做any类型来处理的, 这很容易造成经典的read property of undefined运行时异常
    "declaration": true,
    "declarationDir": "dist",
  },
  "typedocOptions": {
    "entryPoints": ["src/tsdoc/**/*.ts"],
    "out": "tsdoc",
    "includeVersion": true, // 生成文件带有package.json 版本号
  }
}

下面列出一部分常用的注释

@igonre @hidden 忽略内容,在文档中不展示


@enum 枚举


@example 举个栗子


@packageDocumentation 用于表明当前引入的详细描述


@param 函数、类的参数


@privateRemarks 在文档中不应被使用的


@readonly 只读


@remarks 用于标记一些比较重要的部分


@returns 函数或类的返回值


@see 导出资源相关的文档wiki链接


@throws 抛出的异常

如有问题欢迎指出讨论!