Skip to content

ESLint、Prettier 详细接入指南 #10

@liveKang

Description

@liveKang

ESLint、Prettier 详细接入指南

[TOC]

环境安装

编辑器安装

本文推荐使用 VSCode 编辑器,所有步骤均以 Mac 下 VSCode 为例。

插件安装

安装好编辑器后进行插件安装,shift + command + x 打开 Extensions 面板,搜索安装以下插件。

编辑器配置

User settings

Preferences --> Settings --> open settings.json --> User settings 新增下面的配置。

{
  // ... 
  "eslint.validate": ["javascript", "vue", "html", "javascriptreact"],
  // 关闭自带的 javascript 校验
  "javascript.format.enable": false,
  //保存时eslint自动修复错误
  "eslint.autoFixOnSave": true
}

ESLint 配置文件

项目根目录下新建 .eslintrc.js 文件

React 推荐配置

module.exports = {
	parser: 'babel-eslint',
	extends: ['airbnb', 'prettier', 'plugin:compat/recommended'],
	env: {
		browser: true,
		node: true,
		es6: true
	},
	globals: {
		APP_TYPE: true,
	},
	plugins: ['html'],
	rules: {
		'react/jsx-filename-extension': [1, { extensions: ['.js'] }],
		'react/jsx-wrap-multilines': 0,
		'react/prop-types': 0,
		'react/forbid-prop-types': 0,
		'react/jsx-one-expression-per-line': 0,
		// jsx 统一 tab 4 spaces
		'react/jsx-indent': [0, 'tab'],
		'react/jsx-indent-props': [0, 'tab'],
		'import/no-unresolved': [2, { ignore: ['^@/', '^umi/'] }],
		'import/no-extraneous-dependencies': [2, { optionalDependencies: true }],
		'jsx-a11y/no-noninteractive-element-interactions': 0,
		'jsx-a11y/click-events-have-key-events': 0,
		'jsx-a11y/no-static-element-interactions': 0,
		'jsx-a11y/anchor-is-valid': 0,
		// 禁用分号
		'semi': [2, 'never'],
		// 禁止尾随逗号
		'comma-dangle': [2, 'never'],
		// 强制使用 tab 缩进
		'indent': [2, 'tab']
	},
	settings: {
		polyfills: ['fetch', 'promises', 'url'],
	},
};

Vue 推荐配置

// https://eslint.org/docs/user-guide/configuring

module.exports = {
	root: true,
	parserOptions: {
		parser: "babel-eslint"
	},
	env: {
		browser: true
	},
	globals: {
		scHybridBridge: true
	},
	// https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
	// consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
	extends: ["plugin:vue/essential", "airbnb-base"],
	// required to lint *.vue files
	plugins: ["vue"],
	// add your custom rules here
	rules: {
		// Ensure imports point to a file/module that can be resolved
		"import/extensions": [2, { ignore: [".js", ".json"] }],
		"import/no-unresolved": 0,
		// disallow reassignment of function parameters
		// disallow parameter object manipulation except for specific exclusions
		"no-param-reassign": [
			"error",
			{
				props: true,
				ignorePropertyModificationsFor: [
					"state", // for vuex state
					"acc", // for reduce accumulators
					"e" // for e.returnvalue
				]
			}
		],
		// allow optionalDependencies
		"import/no-extraneous-dependencies": [
			"error",
			{
				optionalDependencies: ["test/unit/index.js"]
			}
		],
		// 禁用分号
		semi: [2, "never"],
		// 禁止尾随逗号
		"comma-dangle": [2, "never"],
		// 强制使用 tab 缩进
		indent: [2, "tab"],
		// 关闭禁用 tab
		"no-tabs": 0,
		// 单行最大长度 200 字符串
		"max-len": [2, { code: 200 }],
		"no-use-before-define": [2, { functions: false, classes: true }],
		// 关闭禁用 ++ 或 --
		"no-plusplus": [0],
		// 关闭使用字面量对象
		"object-shorthand": 0,
		// 关闭函数表达式必须有名字
		"func-names": 0
	}
};

忽略文件配置

在项目根目录下新建 .eslintignore

/script
/functions
/mode_modules
/dist
/.vscode
/.temp
/.circleci
*.ejs
.*
*.json

【注意】项目需要先安装eslint依赖,npm install eslint -D,也可以全局安装sudo npm install eslint -g

Git hooks 集成 ESLint

Git hooks: Git 提供的提交工作流钩子,可在该钩子中执行ESLint代码校验。

集成Git hooks有两种方案,一种利用原生的Git hooks事件,Git钩子

第二种为pre-commit解决方案,具体操作如下:

安装 pre-commit

npm install pre-commit -D

示例 package.json

{
  "name": "changshu-smt-web",
  "version": "1.0.0",
  "description": "",
  "author": "xxx",
  "private": true,
  "scripts": {
    // ...
    // 配置以下三个指令
    "lint": "eslint --fix --ext .js,.vue src",
    "precommit": "npm run lint",
    "precommit-msg": "echo 'Pre-commit checks...'"
  },
  "pre-commit": [
    "precommit-msg",
    "precommit"
  ],
  "dependencies": {
    ...
  },
  "devDependencies": {
    "pre-commit": "^1.2.2",
    ...
  }
  ...
}
名称 说明
lint 指定eslint执行的校验范围,及修复部分问题
precommit 调用lint命令
precommit-msg 开始校验的提示语

其他配置文件参考

.editorconfig

root = true

[*]
charset = utf-8
indent_style = tab
indent_size = 4
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

.prettierrc

{
	"singleQuote": true,
	"trailingComma": "none",
	"printWidth": 100,
	"semi": false,
	"tabWidth": 4,
	"useTabs": true,
	"overrides": [
		{
			"files": ".prettierrc",
			"options": { "parser": "json" }
		}
	]
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions