Original post: https://manhhomienbienthuy.bitbucket.io/2018/May/20/we-should-use-eslint-in-project.html (author’s permission obtained)

)

JavaScript has become an extremely popular language in web programming. Nearly any web developer must know JavaScript code. But knowing is one thing, good code is another. In this article, I will introduce a tool to help us code better JavaScript, which is ESLint.

Watching: Minimize jagged code with eslint

Preamble

JavaScript has evolved far beyond its early generations, when the ES2015 (ECMAScript 2015 – ES6) and ES2017 specifications were published. In particular, many JavaScript libraries such as ReactJS, AngularJS, VueJS, etc. help us to build extremely cool web applications.

Despite such specifications, coding JavaScript today is still very problematic. Therefore, ensuring the quality of JavaScript code has always been a big challenge.

There are many good elements to creating a good project such as: clear directory structure, informative README, setup instructions as well as build, test. And the most important element of a good project should be code that is easy to read, understand and maintain.

To ensure those factors, human power cannot do it all. That’s when we need the lint tools.

What is Lint?

If you want a project to have good enough code, you need to build coding conventions from the very beginning for everyone to follow. Coding conventions don’t usually make code run faster, but they help maintain code that’s easier to read.

I’ve been through a number of projects, and actually using humans to ensure coding conventions is unthinkable because of too much work. Well, even humans sometimes make mistakes, can ignore this error, that error if it is small during the review. Therefore, it is best to ensure the coding convention with automated tools.

Things of such a fixed nature, computers always do better than humans. The results are both accurate and fast, developers will have more time to create and write code for functions, rather than scrutinizing other people’s semicolons to be correct. Tools that help us do this are called lint (linter) tools.

Lint are tools that help us analyze the code, thereby showing the problems that the code is facing such as non-compliance with coding style, wrong coding convention. In addition, lint can also help us find some potential bugs in the code such as assigning undeclared variables, which can cause runtime errors, or getting the value from a global variable that makes debugging difficult, etc. …

Lint can give some people a headache at first, but it will make the code clearer. Gradually, as the process increases, lint will be a very useful test aid.

Why JavaScript?

If you are a NodeJS coder, there is no doubt about it. JavaScript is the main language used, so we need linter for it of course.

Here, I mean other web development projects where many different languages ​​are used, from the backend (Ruby, PHP, Python, etc.) to the frontend (HTML, JavaScript, SCSS, etc.) …)

In a project, all languages, including HTML and CSS, must follow the rules to create a good project. Without rules, people coding in very different styles will create a mess that outsiders won’t understand (they don’t even want to read).

However, in the content of this article, all of the major languages ​​are JavaScript. JavaScript may not be the most important language in the project, but I can say for sure that it is the language that needs linter the most.

The reason comes from the language itself. JavaScript has a bad design, its syntax is a mixture of Java and C++, and mixes many features of scripting languages ​​like Ruby, Python.

Not to mention, this language is supported on different browsers very differently. Each browser uses its own engine, so many functions that work in one browser may not work in another. Surely any of us have had nightmares with InteExplorer. In order for the code to run in multiple browsers, it is almost imperative that the code has redundant code beyond the logic.

Because of syntactic complexity, JavaScript has a lot of problems. You can read more here. The release of ES2015 only alleviated its problems, not eliminated it entirely. Not to mention performance things, even its syntax makes it very ‘flexible’. We can add spaces and line breaks at will, making it the language that can code in the most styles in a project.

READ MORE  What is a Png Image

So, as the project progresses over time, the code will gradually increase every day, each developer has different styles and likes when coding, even the same person who codes one style now, tomorrow codes another. , which makes JavaScript the most difficult language to homogenize in a project.

Even when there is a coding convention, two people coding the same logic still can produce code that looks “unrelated” to each other.

One factor that makes it difficult for JavaScript to maintain consistency in the way code comes from humans. Most of the full stack developers that I know are only strong in the backend, they have skills in the frontend but compared to the backend, it’s really a world. Moreover, the frontend is an easily overlooked part of the project, as people focus more on performance, code optimization, database, etc.

Recently, especially after the appearance of ReactJS, JavaScript has become more and more important in the project. Instead of just a small part, supporting a few effects to make the page more beautiful, JavaScript now takes over the “display” part of the page completely. Especially in many projects, the frontend is only JavaScript and CSS, pure HTML is almost no longer used.

With such projects, lint JavaScript is more necessary than ever.

Why choose ESLint?

There are many different JavaScript lint engines: ESLint, JSLint, JSHint.

There is a comparison of these tools, you can read for reference. The tools can be summarized as follows: JSLint is very restrictive, not allowing us to customize to our liking, JSHint lacks extension mechanisms, JSCS is only suitable for checking coding style.

And finally ESLint is the most harmonized tool, the best choice for projects. It allows us to customize the configuration according to our coding conventions, check the coding style and find bugs and other potential problems.

ESLint is even more an extremely suitable choice if we use ES2015 as well as JSX (of React). Out of all the linters, it is the best ES2015 JSX supporter and the only one that currently supports JSX.

Of course, more features mean it will run slower. So in some projects it may not be the most appropriate tool. However, my personal opinion is, it suits most, so it’s okay to use it.

Install and configure ESLint

ESLint can be installed via npm simply as follows

$ npm install –save-dev eslint It’s not necessary to code NodeJS to use node and npm. Many projects have used node packages to build frontend components. So, maybe I don’t need to say more about npm, if not clear, you can refer to it here.

In addition, ESLint also allows us to use plugins to extend its operation. For example, I code ReactJS in my project, I need to install the following plugin so that ESLint can support it:

$ npm install –save-dev eslint-plugin-react A good linter can only work if we configure it correctly. Otherwise, instead of serving to improve the quality of our code, it becomes a hindrance by constantly bringing up bugs for the wrong places.

See also: What is Dwt – Gt And How It’s Different

ESLint is a very flexible tool, allowing us to configure it very easily. Everything related to the coding convention is configurable. There are two ways to configure ESLint, the first way is to comment directly in the JavaScript code. Kind of like this:

/* eslint quotes: , curly: 2 */ This way has a disadvantage that for each file, we have to configure it once, but many times this number of comments is very large because we need to configure many different things in the convention. So the more efficient way is to use a common config file that applies to the entire project. But we can still use comments in some files if those files are required to code differently from the general rule.

ESLint uses a config file, named .eslintrc.*, the extension can be js, yaml, yml, json corresponding to that file’s format, or write the config directly to the package.json file.

Personally, I prefer to use JSON, so I will configure ESLint in the .eslintrc.json file. Using package.json is always convenient, but that will make the file unnecessarily large, so I think it’s better to use a separate file.

READ MORE  Visual effects

The config file for ESLint has the following main components:

plugins

These are plugins used to extend the operation of ESLint. For example, ESLint does not support the holy JSX syntax checking, then it is imperative that we use a plugin to check those codes.

{ “plugins”: < "react" >, …}extensions

These are the existing configs used, we will extend them by adding our own configs. ESLint has a pretty cool mechanism that allows us to “reuse” other people’s configurations. For example, I want to use the built-in configuration eslint:recommended (built into eslint), and react/recommended (built into the plugin), then I configure the following:

{ … “extends”: < "eslint:recommended", "plugin:react/recommended" >, …} Similarly, we can use everyone’s configuration if we feel it is appropriate, for example strongloop for example. We can install the corresponding package and extend it. Note that, we should learn more about these available configurations, sometimes they are very convenient, but if not suitable, they should not be used, even “recommended” configurations.

rules

This is the part config what rules the code needs to follow. There are many pre-configured rules, when we extend a configuration, there is no need to configure it again. Here, we just need to configure more rules that we need to customize.

Each rule needs to be configured with two parameters: the value corresponding to the level of rule applied (off, warn, error or 0, 1, 2 for brevity) and options. Rules here can be rules provided by ESLint or rules of the plugin.

For example, the following rule requires applying single quote ” to strings in the code, and checking if the import of React is correct, otherwise it will give an error with the exit code of 1.

{ … “rules”: { “quotes”: < 2, “single” >, “react/jsx-uses-react”: 2, … } …} The number of rules that ESLint supports is very large, almost all of the elements. All elements of the code are supported, not to mention the plugin is even more extensible. You can view the full ESLint rules here.

parserOptions

By default, ESLint checks the syntax of ES5, if using ES6 or later, we must configure it with parserOptions. In addition, JSX support also needs to be configured here. The full configuration for this part is as follows:

{ … “parserOptions”: { “ecmaVersion”: 6, “sourceType”: “module”, “ecmaFeatures”: { “jsx”: true } }, …}env

This is where we configure the environment in which our code will run. Different environments have different global variables. For example, the browser environment will have variables like window, document, and the es6 environment will have some new data types like Set.

{ … “env”: { “browser”: true, “es6”: true }, …}globals

This is where we come up with the list of global variables used in the project. Otherwise, when we access a certain variable, ESLint will give an error because the access to a variable has not been defined.

Global variables can be defined with comments in the file itself, or a complete list in the config file.

Some global variables do not need to be redefined (like window, document) if env already defines it.

JavaScript has an object that contains the data passed to the function arguments, which does not see an environment that defines it. If we want to use this object, we must include it in the globals of config.

{ … “globals”: ​​{ “arguments”: true, … }} In addition to the main parts as presented, ESLint has many other configs. You can refer here for more details on customizing ESLint to your liking.

Example

Below is the full configuration of ESLint that I am using to lint React (Redux) code.

{ “plugins”: < "react" >, “extends”: < "eslint:recommended", "plugin:react/recommended" >, “rules”: { “indent”: < 2, 2, { "SwitchCase": 1 } >, “linebreak-style”: < 2, “unix” >, “quotes”: < 2, “single” >, “semi”: < 2, “always” >, “curly”: < 2, " all" >, “camelcase”: < 2, { "properties": "always" } >, “eqeqeq”: < 2, "smart" >, “one-var-declaration-per-line”: < 2, " always" >, “new-cap”: 2, “no-case-declarations”: 0 }, “parserOptions”: { “ecmaVersion”: 6, “sourceType”: “module”, “ecmaFeatures”: { “jsx” : true } }, “env”: { “browser”: true, “es6”: true }, “globals”: ​​{ “arguments”: true }}Apply ESLint to the project After configuring ESLint is complete, the All that’s left is to apply it to the project, making it work like a linter.

First of all, we need to add a script to call later like this (package.json file):

READ MORE  Find Out And Compare What Is Mbr With Gpt And What Is Mbr

{ … “scripts”: { “eslint”: “eslint path/to/src”, … } …} Which script to use depends on the project. If it’s a NodeJS project, we can use the script preset or posttest, so that ESLint is run automatically every time the unit test is called. With a regular web project, you can name the script so that it’s easy to remember.

After we have the script, every time we need to call ESLint, we just need to simply:

$ npm run eslint > eslint /absolute/path/to/package> eslint –fix path/to/src/absolute/path/to/file.js 14:8 error “moment” is defined but never used no-unused-vars 163:30 error “states” is missing in props validation react/prop-types✖ 2 problems (2 errors, 0 warnings)If you have never used linter, or for the inexperienced, it is possible that every time you run lint, is one (several) screen pages full of errors. For people with weak psychology, they may be shocked and depressed and do not want to code anymore.

Thankfully with ESLint, they helped us with (part of) the problem. ESLint can automatically fix some errors automatically by adding the -fix option, we can add this option right into the script above, or call it manually

$ npm run eslint — –fixESLint can fix a lot of errors, but not all. It can only fix the code that is guaranteed not to affect the operation. However, it has helped us a lot, at least the number of bugs has been significantly reduced, looking at it will see more future.

If you want a more powerful debugging tool, you can use prettier (reference). This is a tool that specializes in code formatting, so it is more powerful than ESLint in debugging. Using a combination of ESLint and prettier will give very good results (although it cannot be 100% corrected).

Automate everything

Above, I was demonstrates how to apply ESLint to a project, by typing commands as needed. Having to type the same command dozens of times a day is indescribably boring, at least for me. So if there is a way to automate everything, that would be perfect.

After researching, I found a way, which is to use git hook pre-commit. Using git hook will help us to run ESLint every time we commit. If you’ve used git hook pre-commit before, you just need to edit the .git/hooks/pre-commit file, otherwise we need to create that file.

The easiest way is to use the sample file git itself provides:

$ cp .git/hooks/pre-commit.sample .git/hooks/pre-commitThe file content will have the last two lines as follows:

# If there are whitespace errors, print the offending file names and fail.exec git diff-index –check –cached $against –We will add the ESLint call as follows:

set -enpm run eslint# If there are whitespace errors, print the offending file names and fail.exec git diff-index –check –cached $against –So now, every time you commit, ESLint will be called, fully automatically :

$ git commit -m “WIP”> eslint /absolute/path/to/package> eslint –fix path/to/src WIP 1 file changed, 3 insertions(+), 3 deletions(-)Also, maybe we still use watchify to track changes in code and auto-build again. However, watchify makes it very difficult to call ESLint every time it changes. If we want, we have to switch to using other build tools like gulp or grunt.

These two tools allow us to customize a lot, they have a mechanism that allows running more than one task when a file changes. The downside is that watchify has a cache mechanism that makes building code when there are changes a lot faster, using gulp or grunt the build code will always be done from scratch so it takes more time. (However, watchify’s cache mechanism has some problems when adding and deleting files.)

Another emerging tool is webpack which also allows us to use eslint calls very conveniently, using eslint-loader.

Configuring these tools is another matter, beyond the scope of this article, so I will not cover much here. Note that, unlike using git hooks, using these tools will apply automation to the entire project, which is great, but not everyone likes it. So if you want to apply, you should find consensus with your colleagues.

See also: What Year is 2012?

Conclude

ESLint is a great tool, use it often. Hope the article will be of some help to you and your code will become more and more beautiful.