webpack2集成eslint
source link: https://segmentfault.com/a/1190000008575829
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
webpack2集成eslint
规范自己的代码从ESlint
开始。ESlint
和webpack
集成,在babel
编译代码开始前,进行代码规范检测。
这里没有使用像airbnb
等一些厂发布的代码规范,因为每个团队的都有自己的代码风格,这里选用的javascript-style-standard
这个大家用的比较多的风格指南。具体文档请戳我
需要这几个npm包:
eslint
eslint-loader
eslint-plugin-html
(用以lint一些在html文件里面通过script包裹的js代码,它默认的匹配规则是不带type
属性,或者是`/^(application|text)/(x-)?(javascript|babel|ecmascript-6)$/i`,具体的内容请查阅相关文档,通过cli
启动lint
的时候定义文件后缀名时eslint --ext .html,.js
)eslint-config-standard
(和?2个包都是javascript-style-standard
风格指南需要的包)eslint-plugin-promise
eslint-plugin-standard
eslint-friendly-formatter
(生成的报告格式)
这个地方主要说下如果将eslint
集成进webpack2
,关于eslint
具体的文档及使用,请戳我
关于eslint
的配置方式。比较多元化:
js
注释.eslintrc.*
文件package.json
里面配置eslintConfig
字段
这里我选用了.eslintrc.js
文件进行配置,个别文件代码不需要进行lint
的可以使用js
注释在文件中单独标识。
文件.eslintrc.js
内容为:
module.exports = {
root: true, // eslint找到这个标识后,不会再去父文件夹中找eslint的配置文件
parser: 'babel-eslint', //使用babel-eslint来作为eslint的解析器
parserOptions: { // 设置解析器选项
sourceType: 'module' // 表明自己的代码是ECMAScript模块
},
// https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
extends: 'standard', // 继承eslint-config-standard里面提供的lint规则
// required to lint *.vue files
plugins: [ // 使用的插件eslint-plugin-html. 写配置文件的时候,可以省略eslint-plugin-
'html'
],
// 启用额外的规则或者覆盖基础配置中的规则的默认选项
rules: {
// allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
'generator-star-spacing': 0,
// http://eslint.org/docs/rules/comma-dangle
'comma-dangle': ['error', 'only-multiline'],
'semi': 0
},
globals: { // 声明在代码中自定义的全局变量
'CONFIG': true
},
env: { // 定义预定义的全局变量,比如browser: true,这样你在代码中可以放心使用宿主环境给你提供的全局变量。
browser: true, // browser global variables.
node: true, // Node.js global variables and Node.js scoping.
worker: true, // web workers global variables.
mocha: true, // adds all of the Mocha testing global variables.
phantomjs: true, // PhantomJS global variables.
serviceworker: true // Service Worker global variables.
}
}
webpack2
...
module.exports = {
///
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: [
'babel-loader',
'eslint-loader'
],
query: {
cacheDirectory: true
}
},
{
test: /\.vue$/,
enforce: 'pre', // 在babel-loader对源码进行编译前进行lint的检查
include: /src/, // src文件夹下的文件需要被lint
use: [{
loader: 'eslint-loader',
options: {
formatter: require('eslint-friendly-formatter') // 编译后错误报告格式
}
}]
// exclude: /node_modules/ 可以不用定义这个字段的属性值,eslint会自动忽略node_modules和bower_
}
]
}
}
package.json
文件
{
...
"lint": "eslint --ext .js,.vue src"
...
}
通过npm run lint
进行代码的静态检查
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK