前语

上一章:从零搭一个极简版 webpack+React 工程(五)

一番折腾,作者现已简略搭建出一个 webpack + react + TS 的工程;现在界说一下代码风格。究竟团队工作,良好的代码风格仍是能够协助团队进步一下效率的。

安装 eslint

全局安装 eslint

npm i eslint -g

装备文件初始化

eslint --init

How would you like to use ESLint?

  • To check syntax only
  • To check syntax and find problems
  • To check syntax, find problems, and enforce code style

What type of modules does your project use?

  • JavaScript modules (import/export)
  • CommonJS (require/exports)
  • None of these

Which framework does your project use?

Does your project use TypeScript?

  • Yes
  • No

Where does your code run?

  • Browser
  • Node

How would you like to define a style for your project?

  • Use a popular style guide
  • Answer questions about your style

Which style guide do you want to follow?

  • Airbnb: https://github.com/airbnb/javascript
  • Standard: github.com/standard/st…
  • Google: github.com/google/esli…
  • XO: github.com/xojs/eslint…

What format do you want your config file to be in?

  • JavaScript
  • YAML
  • JSON

等候 eslint 安装

Would you like to install them now with npm?

  • Yes
  • No

绵长的等候,当看到这句话 eslint 安装完结

Successfully created .eslintrc.js file in

默认 eslint 装备

安装完 eslint 根目录会生成 .eslintrc.js 这个文件

module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: ['plugin:react/recommended', 'airbnb'],
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: ['react'],
  rules: {
      // 这里写一些eslint规矩
  },
};

安装 @types/react @types/react-dom

npm i @types/react @types/react-dom -D

主动格式化代码

新建 .vscode/settings.json

{
  "prettier.semi": true,
  "prettier.singleQuote": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "[markdown]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[json]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javascriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

vscode修改器插件

  • Prettier – Code formatter
  • ESLint

vscode这两个插件协助代码修改过程中个格式化代码