What 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中文网其它相关文章!
推荐阅读:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to delete eslint from react: 1. Execute the "npm run eject" command; 2. Modify the code in package.json to ""eslintConfig": {"extends": ["react-app","react-app/jest" ],"rules": {"no-undef": "off"...}"; 3. Restart the project.

"SpongeBob SquarePants in the Krusty Krab" is a cooking simulation business game with fast-paced gameplay and full of surprise dishes. You will play SpongeBob and expand various restaurants and kitchens in the game to bring joy. For novice players, here are some strategy suggestions: First, arrange the kitchen layout rationally to improve work efficiency; second, pay attention to the procurement and storage of ingredients to ensure adequate supply; also pay attention to customer needs and process orders in a timely manner; finally, constantly upgrade equipment and recipes to attract more customers. Through these skills, you will be able to get better in the game SpongeBob SquarePants and the Krusty Krab Beginner's Tutorial 1. There is a small goal at the beginning. Players only need to complete the goal to pass the level; 2. During the production process , everyone must carefully check the customer's needs; 3. Every time you complete a

Little Time in Cow Town is a casual farming game that is loved by players. The game sets a leisurely pace and relaxed gameplay, allowing players to create their own interesting stories in the world of simulated towns. Many novice players are interested in this unique business simulation game. Here, I will share with you some introductory gameplay strategies suitable for novices to help them start the game better. Little Time in Cow Town Beginner Game Guide Little Time in Cow Town is an open mobile game that simulates rural life. In this small pixel world, you will experience land reclamation, animal husbandry, building a manor workshop, and conquering the town. Residents and other new farm life, as well as fishing and horse racing, mining adventures, market trade and other diverse gameplay, are waiting for you to experience this new cow town. big

Buried points have always been an important part of the H5 project, and buried point data is an important basis for later business improvement and technical optimization. In daily work, students from product or business departments often come to ask, "What are the hidden points in this project now?", "Where is this hidden point used?" Questions like this are basically asked and checked. The code is very inefficient.

How should new players of Dream City operate? Dream City is a high-quality simulation management game with beautiful and healing content. It provides a lot of free and open city construction and management. It is created with fun and outstanding content, and can be played in depth with a dream rhythm. Exploration, new players are also curious about how to operate. This issue brings a guide to the Dream City beginners! Introduction to the introductory gameplay of Dream City 1. When the Dream City level tree reaches level 3, the land reclamation function is unlocked. Land reclamation requires a dispatched animal, and at the same time It consumes a certain amount of water elements, earth elements, wood elements and gold coins, but some wastelands only require gold coins. 2. Each time you open up wasteland, you can only choose wasteland connected to the unlocked land. Different wastelands require different amounts of materials. As the number of times you open up wasteland increases, the demand for materials in the later period will also increase.

"Ragnarok Love Like First Meeting" is a high-quality Japanese cartoon-themed character game that combines elements of classic IP and cool adventure MMO. The unique operating features of the game create an immersive gaming experience full of classic world views. In the game, players will play various classic professions and explore new adventure stories. For new players, here are some strategy suggestions: Ragnarok Love is Like First Met Beginner Strategy Tips 1. Familiarize yourself with the game operations: Ragnarok Love Is First Met uses virtual buttons to operate. It is recommended that novices familiarize themselves with game operations, including movement, Attack, skill release, etc. 2. Choose a suitable profession: There are a variety of professions to choose from in the game. Novices should choose a suitable profession according to their own gaming preferences and playing habits. 3. Complete tasks to increase your level

How should novice players of Yiyou Thirteen Ways play? Yiyou Thirteen Ways is an awesome immortal cultivation game with exciting content of placing and collecting characters. It provides casual and interesting entertainment, allowing players to experience various aspects of the world of immortality. New players are also very interested in all kinds of high-quality entertainment. This issue brings some help guides for beginners! Yiyou Thirteen Ways Novice Development Guide 1. Daily Challenge: You can consider wearing Chaos Beads to fight every day. Daily challenge rewards are tied to damage, and the higher the damage done, the better the rewards are likely to be. 2. Trial: By challenging level NPCs, you can obtain star stones and fairy jade. If you rank high on the rankings, you can obtain star advanced materials. 3. Main line and elite levels: You can try more. If you are lucky, you will have a chance to trigger the skill effect a few more times.

1. About BBX.com BBX.com is a leading cryptocurrency index contract trading platform that operates globally and is committed to providing users with a safe, convenient and advanced cryptocurrency trading experience. It is the first trading platform to support forward perpetual contracts of BTC, ETH, EOS and BCH with USDT as margin settlement, and also the first trading platform to support perpetual contracts of small currencies. Supports contract transactions, spot transactions and legal currency transactions. 2. BBX account registration and login 1. Use a browser to log in to the BBX official website: https://www.bbx.com/; (Google Chrome browser is recommended) 2. Click the [Register] button in the upper right corner of the official website. Currently, mobile phone numbers are supported There are two ways to register and register by email, choose
