Mario34 / blog

🏀 Mario34的博客
0 stars 0 forks source link

前端项目的代码风格校验相关配置 #3

Open Mario34 opened 4 years ago

Mario34 commented 4 years ago

在进行项目开发时统一代码规范十分的重要,这里记录的是我的一些相关操作的经验

eslint相关配置

随着tslint社区和eslint社区的推动,目前推荐使用eslint做ts的风格校验(安装对应的插件即可@typescript-eslint/eslint-plugin),所以不管是js项目还是ts项目,都使用eslint就对了。

The TypeScript Team themselves also announced their plans to move the TypeScript codebase from TSLint to typescript-eslint, and they have been big supporters of this project. More details at https://github.com/microsoft/TypeScript/issues/30553

Migrating from TSLint to ESLint If you are looking for help in migrating from TSLint to ESLint, you can check out this project: https://github.com/typescript-eslint/tslint-to-eslint-config

不同文件类型的校验使用不同的插件

建议在eslint配置中加入extends: ["eslint:recommended"] eslint:recommended规则能够校验出常见的代码风格错误,其他的代码风格规则需要在配置中声明

No rules are enabled by default. The "extends": "eslint:recommended" property in a configuration file enables rules that report common problems, which have a check mark below.

eslint-plugin-react

eslint-plugin-vue

确保上述配置正确,如果你使用的是VsCode编辑器,安装eslint插件,并设置编辑器保存时进行fix操作,能够极大的提升工作效率。在代码编写阶段就能够解决代码风格问题,不必等到commit时在去处理风格不一致问题。 WebStorm用户同样可以实现上述功能,我不太熟悉WebStorm的配置 : )...

使用 husky+lint-staged+prettier 优化代码格式

Mario34 commented 4 years ago

stylelint相关配置

eslint相比,stylelint主要对样式文件进行校验,根据项目所使用的不同样式预处理语言选择合适的插件

stylelint搭配stylelint-scss

module.exports = {
  extends: ['stylelint-config-standard'],
  plugins: [
    'stylelint-scss',
  ],
  rules: {
    //...rules
  }
}

使用stylelint-plugin-stylus,这是目前比较好的方案。需要注意的是,使用stylelint-plugin-stylus时,不要使用stylelint-config-standard,因为部分配置会引起错误。

// stylelint.config.js
module.exports = {
  "extends": [
    "stylelint-plugin-stylus/standard",
  ],
  "plugins": [
    "stylelint-plugin-stylus"
  ],
  "rules": {
     // ...rules
  },
  "ignoreFiles": [
    "ignoreFilePathl"
  ]
}