在实际开发中不免会有协同开发的时候,每一个开发编写代码的风格、提交代码备注信息等方面的风格不尽一致,所以事先统一风格变得尤其重要。本文将在项目中集成eslint、stylelint、commitlint帮助校验JS脚本代码规范、CSS脚本规范以及commit msg规范。javascript
使用create-react-app脚手架搭建示例工程,工程支持typescriptcss
create-react-app react-lint --template typescript
在终端执行下面命令java
npx eslint --init
执行后,终端会出现人机交互,按照本身需求勾选选项便可
最后会提示须要安装如下这些插件node
eslint-plugin-react@latest @typescript-eslint/eslint-plugin@latest eslint-config-standard@latest eslint@^7.12.1 eslint-plugin-import@^2.22.1 eslint-plugin-node@^11.1.0 eslint-plugin-promise@^4.2.1 @typescript-eslint/parser@latest
解释下这些插件的做用:react
执行完npx eslint --init后会在根目录生成.eslintrc配置文件,也能够本身手动建立或者在 package.json 里建立一个 eslintConfig属性,在那里定义你的配置git
module.exports = { env: { browser: true, es2021: true }, extends: [ 'plugin:react/recommended', 'standard' ], parser: '@typescript-eslint/parser', // 将 TypeScript 转换成与 estree 兼容的形式,以便在ESLint中使用 parserOptions: { ecmaFeatures: { jsx: true // 启用 JSX }, ecmaVersion: 12, // 指定你想要使用的 ECMAScript 版本 sourceType: 'module' }, plugins: [ 'react', // eslint-plugin-react的缩写,使ESLint支持 React 语义 '@typescript-eslint' // @typescript-eslint/eslint-plugin的缩写,为TypeScript代码库提供lint规则 ], rules: { semi: [2, 'always'], 'no-use-before-define': 'off' // 'React' was used before it was defined } };
配置好了以后,eslint服务会自动校验.tsx脚本文件,好比语句结尾缺乏分号:github
可是,若是报错的地方比较多了,手动一个一个去改太麻烦了。在VScode中安装eslint拓展插件,而且在.vscode/settings.json中配置保存时自动修复,以下:typescript
// 如何配置在eslint拓展插件中有使用说明 { "eslint.validate": [ "javascript", "javascriptreact", { "language": "typescript", "autoFix": true }, { "language": "typescriptreact", "autoFix": true } ], "eslint.autoFixOnSave": true, "editor.codeActionsOnSave": { "source.fixAll.eslint": true, }, "eslint.enable": true, }
当Ctrl+S保存时会自动修复代码格式化问题。json
stylelint用来校验CSS脚本语法、格式问题promise
安装stylelint、stylelint-config-standard,stylelint-config-standard继承stylelint-config-recommended,提供一些经常使用的CSS规则,是stylelint推荐的配置
yarn add stylelint stylelint-config-standard -D
在根目录下生成.stylelintrc.json配置文件,并根据以下初始化配置
{ "extends": "stylelint-config-standard" }
安装stylelint-order、stylelint-config-rational-order,stylelint-order是
stylelint-config-rational-order提供了CSS顺序的规则。这两个插件能够帮助矫正样式顺序
{ "extends": ["stylelint-config-standard", "stylelint-config-rational-order"], "plugins": ["stylelint-order"], "rules": { "string-quotes": "single" } }
stylelint-config-rational-order提供的规则中排除了对scss中'composes', '@import', '@extend', '@mixin', '@at-root'
这些属性的处理