JavaScript代码风格
1. 规范
为了约定大家的代码风格,在社区中诞生了一些比较规范的代码风格规范:
2. ESLint
ESLint 只是提供了工具和规则,如何配置这些规则完全取决于使用者。这里使用 Airbnb 配置来说明。
2.1. 安装
参考:https://www.npmjs.com/package/eslint-config-airbnb
$ npm info "eslint-config-airbnb@latest" peerDependencies
{ eslint: '^4.19.1',
'eslint-plugin-import': '^2.12.0',
'eslint-plugin-jsx-a11y': '^6.0.3',
'eslint-plugin-react': '^7.9.1' }
$ npx -v
6.1.0
$ npx install-peerdeps --dev eslint-config-airbnb
+ eslint-config-airbnb@17.0.0
+ eslint-plugin-jsx-a11y@6.1.1
+ eslint-plugin-react@7.10.0
+ eslint-plugin-import@2.13.0
+ eslint@4.19.1
SUCCESS eslint-config-airbnb and its peerDeps were installed successfully.
2.2. 配置
# 创建 package.json
$ npm init -y
$ eslint --init
? How would you like to configure ESLint?
Answer questions about your style
❯ Use a popular style guide
Inspect your JavaScript file(s)
? Which style guide do you want to follow?
Google
❯ Airbnb
Standard
? Do you use React? No
? What format do you want your config file to be in? JSON
+ eslint-plugin-import@2.13.0
+ eslint-config-airbnb-base@13.0.0
最后生成 .eslint.json
文件:
{
"extends": "airbnb-base"
}
2.3. 使用
2.3.1. 在命令行中
$ ./node_modules/.bin/eslint -v
v4.19.1
$ ./node_modules/.bin/eslint ./blog/
/Users/forwardNow/develop/work/study/blog/2018/08/test.js
35:1 warning Unexpected console statement no-console
✖ 1 problem (0 errors, 1 warning)
2.3.2. 配置 npm script
"scripts": {
"eslint": "./node_modules/.bin/eslint ./src/"
},
2.3.3. 在 vscode 中
搜索并安装 eslint 插件
配置 User Settings:
"editor.detectIndentation": false,
"editor.tabSize": 2,
"eslint.autoFixOnSave": true,