1. 全局安装eslint npm i -g eslint
2. 在工程文件夹下运行eslint --init
弹出对话框,选择Answer questions about your style
,接下来回答问题:
* How would you like to configure ESLint?
* Are you using ECMAScript 6 features? //是否用到ES6?选择Y
* Are you using ES6 modules? //是否用到ES6模块?如果写node,选N,写前端,选Y
* Where will your code run? //选择后端node或者前端 Browser
* Do you use JSX? //是否用JSX,不写react选N
* What type of indentation style do you use? //缩进使用tab或者空格?个人喜好吧,我喜欢用tab
* What quotes do you use for strings? //字符串用单引号还是双引号?我个人喜欢单引号
* What line endings do you use?//linux/mac上选择Unix,windows选择windows(废话)
* Do you require semicolons? //行尾是否需要添加分号?选Y,不加会有一些潜在问题
* What format do you want your config file to be in? //使用js或者json来定义?我选择json
生成的.eslintrc.json
文件如下:
{
"env": {
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"rules": {
"indent": [
"error",
"tab"
],
"linebreak-style": [
"error",
"windows"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"no-console": 0,//手动添加
"eqeqeq": 2//手动添加
}
}
基本就是前面回答问题的时候的内容,注意最后两个是手动添加的
第一个no-console
, 表示使用console.log()
等方法,不加这个会报错
eqeqeq
表示使用===
和!==
,严格一点
后面的数字,0表示禁用,1表示出现这个问题显示为警告,2表示错误
其他配置 参见eslint官网完整配置清单
3. 如果你的vscode没有装插件,装eslint
插件
eslint plugin
eslint plugin
4.打开vscode设置:File | Preferences | User Settings
,改变以下几项:
{
"eslint.enable": true,//启用eslint
"eslint.autoFixOnSave": true,//保存时自动lint
"files.eol": "\n",//如果你在linux/mac上开发,请添加这一项,windows请忽略
"editor.insertSpaces": false//禁止自动添加空格,因为我们前面定义使用tab缩进,如果你使用空格缩进请忽略
如果写vue项目,再加上以下配置:
"eslint.validate": [
"javascriptreact",
"html",
{ "language": "vue", "autoFix": true },
{ "language": "javascript", "autoFix": true }
],
5. 其它配置
- 如果你想使用typescript,运行
npm install -g typings
typings install dt~node --global
- 在项目根目录下创建
jsconfig.json
文件以便使用vscode的智能提示:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs"
}
}
愉快玩耍吧少年