search
HomeWeb Front-endJS TutorialWhat you need to know about EsLint for newbies

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

Generate configuration file

$ ./node_modules/.bin/eslint --init

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

$ ./node_modules/.bin/eslint index.js

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

After generating the configuration file

$ eslint --init

, you can run ESLint in any file or directory

$ eslint index.js

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

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

$ npm install -g eslint

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}));

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

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

Use eslint to check

$ eslint index.js
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

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

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

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"
        ]
    }
};

 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"
  };

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)

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',
    },
};

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',
    }
};

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
},

globals: additional global variables

globals: {
    vue: true,
    wx: true
},

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 : 处理方式

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*/

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' ],
    },
};

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

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

  这个要测试的是啥呢,就是看看限定缩进是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.

  这时候提示第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'

然后,我们在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}));

执行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.

然后我们在执行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!

Statement
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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment