由于环境的多样性以及 EcmaScript
版本的不同,Eslint
支持进行环境方面的配置。
3-1. globals
在实际项目中,通常会对全局变量进行限制。
而由于 JavaScript
宿主环境的多样性,可能会有 window
、global
、self
以及 process
等等全局变量。
如果使用第三方库或 SDK
,那么也会有自定义的全局变量,譬如 jquery
、wx
等。
为了代码的严谨性,那么可以对全局变量加以限制。
// main.js
console.log(window)
jquery('#app').show()
// .eslintrc.js
module.exports = {
root: true,
rules: {
"no-undef": ["warn"]
}
}
如上代码,设置 rules
中的 no-undef
属性,这样在执行 npx eslint main.js
后,就会提示:
warning "console" is not defined no-undef
warning "window" is not defined no-undef
warning "jquery" is not defined no-undef
此时,为了解决控制台的报错,可以设置用于指定全局变量的 globals
属性:
// .eslintrc.js
module.exports = {
root: true,
globals: {
window: "readonly",
console: "readonly",
jquery: "readonly"
},
rules: {
// 该规则可指定 变量未定义时报错
"no-undef": ["warn"],
// 该规则可指定 是否允许修改全局变量
"no-global-assign": ["warn"]
}
}
globals
的属性项可以设置:
writable
该属性可写。readonly
该属性只读,可以配合rules
中的"no-global-assign": ["warn"]
来使用。off
该属性将不被指定为全局变量。
TIP
globals
属性的设置,还可以通过设置代码注释来指定:
/* global window: writable, console: readonly */
3-2. env
在实际开发中,会有很多的全局变量。
譬如 browser
环境下,本身就存在许多全局变量,window
、document
、navigator
...
如果每一个变量,都要在上一节的 globals
中进行声明,明显是不太便利的。
因此,我们可以使用 env
来声明,项目所针对的环境,从而自动保证可使用这一类环境下的所有全局变量。
module.exports = {
root: true,
env: {
// 可以同时配置多个 `env` 选项。并不会冲突。
browser: true,
node: true
}
}
env
属性的所有可配置项可见specifying-environments。
在声明了 env
属性的情况下,我们只需要专注于第三方的全局变量即可,以在 browser
环境下使用jquery
和 lodash
为例:
module.exports = {
root: true,
globals: {
$: "readonly",
_: "readonly"
},
env: {
browser: true
}
}
TIP
env
属性的设置,还可以通过设置代码注释来指定:
/* eslint-env browser, node */
3-3. parserOptions
parserOptions
属性用来声明解析的额外配置。
module.exports = {
parserOptions: {
/*
声明ecma版本,默认是5,因此会出现保留字等相关错误。譬如:
Parsing error: The keyword 'const' is reserved
*/
ecmaVersion: 6,
/*
声明类型,是script脚本还是module模块。默认是 script,如果声明的是script,而在代码中使用了EsModule,则会报错:
Parsing error: 'import' and 'export' may appear only with 'sourceType: module'
*/
sourceType: "script",
/*
是否允许用户使用保留字,默认是false。该选项,只有在 ecmaVersion 是3时,才会起作用。
*/
allowReserved: false,
/* ecma 新特性 */
ecmaFeatures: {
/*
是否可在全局作用域下使用return,默认为true
Parsing error: 'return' outside of function
*/
globalReturn: true,
/*
是否启用隐式严格模式,默认为 false
ecmaVersion 需要大于等于 5,且 sourceType 不等于 module,因为 EsModule 默认启用严格模式
*/
impliedStrict: true,
/*
是否启用 jsx 语法,默认不启用
*/
jsx: true
}
}
}
上述中的 impliedStrict
,针对的是严格模式strict mode。
额外说明的一点是 Eslint
只能检测语法层面,无法检测编译阶段。
假设在设置了 impliedStrict
为 true
的情况下,有下列代码:
// ①
var x = 'Hello world'
delete x
// ②
var obj = {
get name() {
return 'Jerry'
}
}
obj.name = 'Tom'
在严格模式下,Eslint
只能检测到 ①
的错误:Parsing error: Deleting local variable in strict mode
。
并不能检测到 ②
的错误。
但代码 ②
在实际编译执行时,会报错:Uncaught TypeError: Cannot set property x of #<Object> which has only a getter
。