Home > Web Front-end > JS Tutorial > body text

What you need to know about EsLint for newbies

php中世界最好的语言
Release: 2018-05-24 14:05:32
Original
3902 people have browsed it

This time I will bring you the instructions for newbies to get started with EsLint. What are the precautions for newbies to get started with EsLint. The following is a practical case, let’s take a look at it together.

Introduction

 ESLint is a plug-in javascript code detection tool that can be used to check Common JavaScript code errors can also be checked for code style, so that we can specify a set of ESLint configurations according to our own preferences, and then apply them to the projects we write to achieve Assist in the implementation of coding standards and effectively control the quality of project code.

Installation

ESLint installation: local installation, global installation

1, local installation

$ npm install eslint --save-dev
Copy after login

Generate configuration file

$ ./node_modules/.bin/eslint --init
Copy after login

After that, you can run ESLint in any file or directory as follows:

$ ./node_modules/.bin/eslint index.js
Copy after login

index.js is the js file you need to test. Any plugins or shared configurations you use (must be installed locally to work with a locally installed ESLint).

2. Global installation

If you want ESLint to be available to all projects, it is recommended to install ESLint globally.

$ npm install -g eslint
Copy after login
Copy after login

After generating the configuration file

$ eslint --init
Copy after login

, you can run ESLint in any file or directory

$ eslint index.js
Copy after login
Copy after login

PS: eslint --init is used for every project Directory that sets up and configures eslint and will execute locally installed ESLint and its plugins. If you prefer to use ESLint installed globally, any plugins used in your configuration must be installed globally.

Use

1. Generate a package.json file in the project root directory (The project that configures ESLint must have a package.json file. If not, you can use npm init -y to generate )

$ npm init -y
Copy after login

2. Install eslint (The installation method is installed according to the needs of personal projects, here we use global installation )

$ npm install -g eslint
Copy after login
Copy after login

3. Create index .js file, write a function in it.

function merge () {
    var ret = {};
    for (var i in arguments) {
        var m = arguments[i];
        for (var j in m) ret[j] = m[j];
    }
    return ret;
}

console.log(merge({a: 123}, {b: 456}));
Copy after login

Execute node index.js, the output result is { a: 123, b: 456 }

$ node index.js
{ a: 123, b: 456 }
Copy after login

Use eslint to check

$ eslint index.js
Copy after login
Copy after login
Oops! Something went wrong! :(

ESLint: 4.19.1.
ESLint couldn't find a configuration file. To set up a configuration file for this project, please run:

    eslint --init

ESLint looked for configuration files in E:\website\demo5\js and its ancestors. If it found none, it then looked in your home directory.

If you think you already have a configuration file or if you need more help, please stop by the ESLint chat room: https://gitter.im/eslint/eslint
Copy after login

The execution result is failure because it is not found Corresponding configuration file, personally think that the most important thing about this eslint is the configuration issue.

New configuration file

  $ eslint --init
Copy after login

During the generation process, you need to select the generation rules, support environment and other content. Here are some of my generation options

? How would you like to configure ESLint? Answer questions about your style
? Are you using ECMAScript 6 features? Yes
? Are you using ES6 modules? Yes
? Where will your code run? Browser
? Do you use CommonJS? Yes
? Do you use JSX? No
? What style of indentation do you use? Tabs
? What quotes do you use for strings? Single
? What line endings do you use? Windows
? Do you require semicolons? No
? What format do you want your config file to be in? JavaScript
Copy after login

The generated content is in. In the eslintrc.js file, the file content is as follows

module.exports = {
    "env": {
        "browser": true,
        "commonjs": true,
        "es6": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "sourceType": "module"
    },
    "rules": {
        "indent": [
            "error",
            "tab"
        ],
        "linebreak-style": [
            "error",
            "windows"
        ],
        "quotes": [
            "error",
            "single"
        ],
        "semi": [
            "error",
            "never"
        ]
    }
};
Copy after login

 However, there are already some configurations in the generated file, so delete most of the content inside. Leave an extension and fill in the rest by yourself

 module.exports = {
      "extends": "eslint:recommended"
  };
Copy after login

eslint:recommended configuration, which contains a series of core rules and can report some common problems.

Re-execute eslint index.js, the output is as follows

  10:1  error  Unexpected console statement  no-console
  10:1  error  'console' is not defined      no-undef

✖ 2 problems (2 errors, 0 warnings)
Copy after login

Unexpected console statement no-console --- Console cannot be used
'console' is not defined no-undef --- console The variables are not defined, and undefined variables cannot be used.
Solve the problem one by one. If you cannot use the console prompt, then we can just disable no-console and add rules

module.exports = {
    extends: 'eslint:recommended',
    rules: {
        'no-console': 'off',
    },
};
Copy after login

to the configuration file. Write the configuration rules In the rules object, key represents the rule name, and value represents the rule configuration.
 Then there is the solution to no-undef: the reason for the error is that JavaScript has many running environments, such as browsers and Node.js. In addition, there are many software systems that use JavaScript as their scripts Engines, such as PostgreSQL, support using JavaScript to write storage engines, and the console object may not exist in these operating environments. In addition, there will be a window object in the browser environment, but not in Node.js; there will be a process object in Node.js, but not in the browser environment.
So we also need to specify the target environment of the program in the configuration file:

module.exports = {
    extends: 'eslint:recommended',
    env: {
        node: true,
    },
    rules: {
        'no-console': 'off',
    }
};
Copy after login

When the check is re-executed, there will be no prompt output, indicating that index.js has completely passed the check.

Configuration

There are two configuration methods: file configuration method and code comment configuration method (It is recommended to use the file configuration form, which is relatively independent and easy to maintain).
Use file configuration: Create a new file named .eslintrc in the root directory of the project, and add some checking rules to this file.

File configuration method

env: What environment will your script run in?
Environment can preset global variables for other environments, such as brower, node environment variables, and es6 environment. Variables, mocha environment variables, etc.

'env': {
    'browser': true,
    'commonjs': true,
    'es6': true
},
Copy after login

globals: additional global variables

globals: {
    vue: true,
    wx: true
},
Copy after login

rules: open rules and the level reported when an error occurs
There are three error levels for rules:

0或’off’:关闭规则。 
1或’warn’:打开规则,并且作为一个警告(并不会导致检查不通过)。 
2或’error’:打开规则,并且作为一个错误 (退出码为1,检查不通过)。

参数说明: 
参数1 : 错误等级 
参数2 : 处理方式
Copy after login

Configuration code comment method

Use JavaScript comments to embed configuration information directly into a file
Example:

忽略 no-undef 检查 
/* eslint-disable no-undef */

忽略 no-new 检查 
/* eslint-disable no-new */

设置检查 
/*eslint eqeqeq: off*/ 
/*eslint eqeqeq: 0*/
Copy after login

There is a lot of configuration and rules content, interested students You can refer here: rules

使用共享的配置文件

  我们使用配置js文件是以extends: 'eslint:recommended'为基础配置,但是大多数时候我们需要制定很多规则,在一个文件中写入会变得很臃肿,管理起来会很麻烦。

  新建一个文件比如eslint-config-public.js,在文件内容添加一两个规则。

module.exports = {
    extends: 'eslint:recommended',
    env: {
        node: true,
    },
    rules: {
        'no-console': 'off',
        'indent': [ 'error', 4 ],
        'quotes': [ 'error', 'single' ],
    },
};
Copy after login

然后原来的.eslintrc.js文件内容稍微变化下,删掉所有的配置,留下一个extends。

module.exports = {
    extends: './eslint-config-public.js',
};
Copy after login

  这个要测试的是啥呢,就是看看限定缩进是4个空格和使用单引号的字符串等,然后测试下,运行eslint index.js,得到的结果是没有问题的,但是如果在index.js中的var ret = {};前面加个空格啥的,结果就立马不一样了。

2:1  error  Expected indentation of 4 spaces but found 5  indent

✖ 1 problem (1 error, 0 warnings)
  1 error, 0 warnings potentially fixable with the `--fix` option.
Copy after login

  这时候提示第2行的是缩进应该是4个空格,而文件的第2行却发现了5个空格,说明公共配置文件eslint-config-public.js已经生效了。

  除了这些基本的配置以外,在npm上有很多已经发布的ESLint配置,也可以通过安装使用。配置名字一般都是eslint-config-为前缀,一般我们用的eslint是全局安装的,那用的eslint-config-模块也必须是全局安装,不然没法载入。

在执行eslint检查的时候,我们会经常看到提示“--flx”选项,在执行eslint检查的时候添加该选项会自动修复部分报错部分(注意这里只是部分,并不是全部

比如我们在规则中添加一条no-extra-semi: 禁止不必要的分号。

'no-extra-semi':'error'
Copy after login

然后,我们在index.js最后多添加一个分号

function merge () {
    var ret = {};
    for (var i in arguments) {
        var m = arguments[i];
        for (var j in m) ret[j] = m[j];
    }
    return ret;;
}

console.log(merge({a: 123}, {b: 456}));
Copy after login

执行eslint index.js,得到结果如下:

  7:16  error  Unnecessary semicolon  no-extra-semi
  7:16  error  Unreachable code       no-unreachable

✖ 2 problems (2 errors, 0 warnings)
  1 error, 0 warnings potentially fixable with the `--fix` option.
Copy after login

然后我们在执行eslint index.js --fix就会自动修复,index.js那个多余的分号也就被修复消失不见了。

总结

以上是我在学习eslint整理的一些资料,不算太全面,对于像我这样的新手入门足够了


相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

前端中排序算法实例详解

PromiseA+的实现步骤详解


The above is the detailed content of What you need to know about EsLint for newbies. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template