Karim Aya

Karim Aya

1563157454

Write beautiful and consistent JavaScript code using ESLint, Prettier and VSCode

Write beautiful and consistent JavaScript code using ESLint, Prettier and VSCode - A short and simple tutorial Bring consistency across your JS code and teams

Proper code styling and formatting is a must for every project and even more so when you have multiple developers working on same codebase. With so many additions to JavaScript following the ECMA standards and different ways to perform a same task there need to be unified standards in your project on what to choose. You will find recommendations all over the internet on what to prefer but still there is no strict rule on what to use. For instance, you may choose to create variables using var instead of the JavaScript’s newlet keyword for scope based variables. So it is upto you to set rules for your project so that every developer on the team follows them and there is consistency across all your code. Here’s where code linting comes into play.

What are linters?

A linter is a program that analyses your source code for possible programmatic and styling errors. Different languages have different linters. ESLint is the linter for JavaScript. Since JavaScript is an interpreted language it is extremely useful to have programmatic errors pointed out before running the application. Here is a programmatic error that ESLint will catch and report to you:

let myFunction = () => {};
myFuction(); // A typo causing error at runtime

For styling errors, ESLint allows you to set rules specific to your project. If you deviate from those rules when writing code ESLint will report them to you. To check out the entire list of rules that ESLint supports follow this link:

List of available rules

Hey, that’s not what I came for, I wanted ESLint setup already.#### Setting up ESLint is super easy.

First we need to install ESLint as a dev dependency:

npm install eslint --save-dev

Next we initialise ESLint for our project:

./node_modules/.bin/eslint --init 

You will then be asked a few questions regarding your preferences to configure ESLint and at the end .eslintrc will be generated.

If you are unsure about the questions you can skip this step. Instead just create .eslintrc manually.

At this point, you have a working ESLint setup for your project. The default ESLint configuration uses rules from eslint:recommended config. However, there is a better alternative in my opinion: eslint-config-airbnb.

Airbnb has created a predefined set of ESLint rules based on Airbnb JavaScript Style Guide. This is an extremely useful resource for all JavaScript developers and tries to establish a common ground for good JS practices. They have reasoned every decision they have taken and give you a chance to understand the same. To get started install the following npm packages as dev dependency:

// For react projects
babel-eslint
eslint-config-airbnb
eslint-plugin-import
eslint-plugin-jsx-a11y
eslint-plugin-react

//For non react projects
babel-eslint
eslint-config-airbnb-base
eslint-plugin-import

Next you need to edit your .eslintrc to extend from Airbnb config. This is how your config would look like:

Also note that you can still write custom rules that will override Airbnb config rules by specifying them in the rules block.

Now ESLint is setup for your project and you can lint your files by running this command: ./node_modules/.bin/eslint [fileName] which will give you an output similar to this:

Great! You can now have consistent code in your project that adheres to the rules you have set up. But we talked about properly formatted code as well, where is that?

Enter, Prettier

Prettier is an opinionated code formatter that has predefined rules for code formatting and indentation. To use prettier in your project run the following command:

npm install --save-dev prettier

This will give you access to Prettier CLI and you can check and perform auto-formatting through a single command:

./node_modules/.bin/prettier --write [fileName]

This command will run prettier on the file and reformat the code. Convenient, isn’t it. Just make sure all your previous changes are saved since this command directly writes to file.

Another good thing about prettier is that it can be configured to use with ESLint wherein it uses eslint rules for code formatting and we can see prettier formatting errors in a file when we run eslint on that file.

**Using Prettier with ESLint **

First you need to install the following npm packages as dev dependency:

eslint-config-prettier
eslint-plugin-prettier

Next we need to configure ESLint to use prettier, so we make the necessary changes to .eslintrc In this case, we just need to add “plugin:prettier/recommended” to the extends block. Combining with our previous configuration the final extends block will look something like this :

"extends": ["airbnb", ""plugin:prettier/recommended""]

Now, you will get Prettier errors included in ESLint errors. The above setup is editor independent and does not require the use of extensions.

We have come far to make our code consistent and beautiful. However, if you noticed, there is no efficiency in this process. We have to run ESLint and prettier on each file through the terminal. For ESLint errors we need to fix the errors and run ESLint again to verify. Well, that is why we have text editors and VSCode is one of the best at it.

VSCode for efficiency

VSCode has extensions for ESLint and Prettier that automate the entire process for you without the need of a CLI. Firstly install these two extensions:

When you restart VSCode and have the above setup for ESLint and Prettier completed, you should be able to see the magic happen. The ESLint errors are now directly visible in the editor without the need of running command through terminal.

You can hover over the red lines to view what the error is. Even better, you can look at the Problems panel in VSCode to get details of all errors present in a file.

Prettier works out of the box as well. Just press cmd + shift + P to open the VS Code commands box and click Format Document and you will have prettified code. Another useful addition is auto-format on save. Click cmd + , to open VSCode settings and add this line to workspace settings: “editor.formatOnSave”:true

Now every time you save your file it will automatically be prettified.

#javascript #web-development

What is GEEK

Buddha Community

Write beautiful and consistent JavaScript code using ESLint, Prettier and VSCode
Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

Karim Aya

Karim Aya

1563157454

Write beautiful and consistent JavaScript code using ESLint, Prettier and VSCode

Write beautiful and consistent JavaScript code using ESLint, Prettier and VSCode - A short and simple tutorial Bring consistency across your JS code and teams

Proper code styling and formatting is a must for every project and even more so when you have multiple developers working on same codebase. With so many additions to JavaScript following the ECMA standards and different ways to perform a same task there need to be unified standards in your project on what to choose. You will find recommendations all over the internet on what to prefer but still there is no strict rule on what to use. For instance, you may choose to create variables using var instead of the JavaScript’s newlet keyword for scope based variables. So it is upto you to set rules for your project so that every developer on the team follows them and there is consistency across all your code. Here’s where code linting comes into play.

What are linters?

A linter is a program that analyses your source code for possible programmatic and styling errors. Different languages have different linters. ESLint is the linter for JavaScript. Since JavaScript is an interpreted language it is extremely useful to have programmatic errors pointed out before running the application. Here is a programmatic error that ESLint will catch and report to you:

let myFunction = () => {};
myFuction(); // A typo causing error at runtime

For styling errors, ESLint allows you to set rules specific to your project. If you deviate from those rules when writing code ESLint will report them to you. To check out the entire list of rules that ESLint supports follow this link:

List of available rules

Hey, that’s not what I came for, I wanted ESLint setup already.#### Setting up ESLint is super easy.

First we need to install ESLint as a dev dependency:

npm install eslint --save-dev

Next we initialise ESLint for our project:

./node_modules/.bin/eslint --init 

You will then be asked a few questions regarding your preferences to configure ESLint and at the end .eslintrc will be generated.

If you are unsure about the questions you can skip this step. Instead just create .eslintrc manually.

At this point, you have a working ESLint setup for your project. The default ESLint configuration uses rules from eslint:recommended config. However, there is a better alternative in my opinion: eslint-config-airbnb.

Airbnb has created a predefined set of ESLint rules based on Airbnb JavaScript Style Guide. This is an extremely useful resource for all JavaScript developers and tries to establish a common ground for good JS practices. They have reasoned every decision they have taken and give you a chance to understand the same. To get started install the following npm packages as dev dependency:

// For react projects
babel-eslint
eslint-config-airbnb
eslint-plugin-import
eslint-plugin-jsx-a11y
eslint-plugin-react

//For non react projects
babel-eslint
eslint-config-airbnb-base
eslint-plugin-import

Next you need to edit your .eslintrc to extend from Airbnb config. This is how your config would look like:

Also note that you can still write custom rules that will override Airbnb config rules by specifying them in the rules block.

Now ESLint is setup for your project and you can lint your files by running this command: ./node_modules/.bin/eslint [fileName] which will give you an output similar to this:

Great! You can now have consistent code in your project that adheres to the rules you have set up. But we talked about properly formatted code as well, where is that?

Enter, Prettier

Prettier is an opinionated code formatter that has predefined rules for code formatting and indentation. To use prettier in your project run the following command:

npm install --save-dev prettier

This will give you access to Prettier CLI and you can check and perform auto-formatting through a single command:

./node_modules/.bin/prettier --write [fileName]

This command will run prettier on the file and reformat the code. Convenient, isn’t it. Just make sure all your previous changes are saved since this command directly writes to file.

Another good thing about prettier is that it can be configured to use with ESLint wherein it uses eslint rules for code formatting and we can see prettier formatting errors in a file when we run eslint on that file.

**Using Prettier with ESLint **

First you need to install the following npm packages as dev dependency:

eslint-config-prettier
eslint-plugin-prettier

Next we need to configure ESLint to use prettier, so we make the necessary changes to .eslintrc In this case, we just need to add “plugin:prettier/recommended” to the extends block. Combining with our previous configuration the final extends block will look something like this :

"extends": ["airbnb", ""plugin:prettier/recommended""]

Now, you will get Prettier errors included in ESLint errors. The above setup is editor independent and does not require the use of extensions.

We have come far to make our code consistent and beautiful. However, if you noticed, there is no efficiency in this process. We have to run ESLint and prettier on each file through the terminal. For ESLint errors we need to fix the errors and run ESLint again to verify. Well, that is why we have text editors and VSCode is one of the best at it.

VSCode for efficiency

VSCode has extensions for ESLint and Prettier that automate the entire process for you without the need of a CLI. Firstly install these two extensions:

When you restart VSCode and have the above setup for ESLint and Prettier completed, you should be able to see the magic happen. The ESLint errors are now directly visible in the editor without the need of running command through terminal.

You can hover over the red lines to view what the error is. Even better, you can look at the Problems panel in VSCode to get details of all errors present in a file.

Prettier works out of the box as well. Just press cmd + shift + P to open the VS Code commands box and click Format Document and you will have prettified code. Another useful addition is auto-format on save. Click cmd + , to open VSCode settings and add this line to workspace settings: “editor.formatOnSave”:true

Now every time you save your file it will automatically be prettified.

#javascript #web-development

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Myah  Conn

Myah Conn

1592827920

How to Write Better Code using ESLint | VSCode ESLint Tutorial

In today’s episode, I am talking about all you need to know about ESLint. You will see what is ESLint and why you need to use ESLint in your JavaScript projects. All the steps to configure and customize it for VSCode are described step by step.

ESLint is a pluggable JavaScript linter that is designed to reduce our mistakes, bad practices, and errors in JavaScript. We can use this linter in order to have a better code format in our team and increase our output quality. If you are working individually or in a team, I highly recommend using ESLint for your projects to avoid mistakes and unwanted errors and have the same code style with your co-workers.

By watching this ESLint tutorial, you will learn how to configure it, disable annoying rules, or define your custom configuration. You will learn how to use it in Vanilla Js or ReactJs or VueJS projects and enable popular configs like Airbnb or standard. At the end of the video, you will see how to enable ESLint auto fix on save for VSCode to make it easier to use.

#vscode eslint tutorial #eslint

5 Best VS Code Extensions for Refactoring that Every Dev Should Know

If you’re looking at ways to clean up our code, reduce complexity and improve functionality - these refactoring extensions will help you move faster:

#refactoring #vscode #javascript #programming #legacy-code #coding #code