Connect with us

Publications

How To Code Better with ESLint and Prettier Configuration

Published

on

NARUHODO Hacker Noon profile picture

@ncribtNARUHODO

Software engineer during the week and apprentice blogger during the weekend. I like JS and Rust.

Before we dive into the topic, you might not know what ESLint and/or Prettier are. ESLint is a JavaScript and TypeScript linting tool. It scans your code and underline potential errors in red and warnings in yellow. It is very useful to improve your code quality and avoid bugs. Prettier is a formatting tool, it supports many languages (JavaScript, TypeScript, CSS, HTML, Markdown, JSON, Yaml, etc). It is useful to keep your code readable and make sure the code format stays consistent when working in a team.

I will first explain how to set them up correctly and run them manually in the terminal, then I will show you how to setup Visual Studio Code to automatically run ESLint and Prettier for you. Finally I will show you how to setup a pre-commit hook that will run ESLint and Prettier before you commit and cancel the commit if ESLint and/or Prettier detect something wrong with your code.

There are already many tutorials out there explaining how to achieve this, but most of them recommend using the eslint-plugin-prettier which basically runs Prettier through ESLint. That is not the recommended way according to the official Prettier documentation. Instead I will show you how to turn off conflicting ESLint rules and then you will be able to run ESLint and Prettier separately and get the best performance.

Before going further, make sure you have Node.js and NPM installed on your machine.

Lets setup a little project. Open your terminal and create a new directory somewhere in your machine

mkdir eslint-prettier-example

Move inside that directory

cd eslint-prettier-example

Initialize a NPM project

npm init -y

Install the following development dependencies

npm install --save-dev eslint eslint-config-prettier prettier

Create a configuration file for ESLint

touch .eslintrc

and add the following content

{ "root": true, "parserOptions": { "ecmaVersion": 2020, "sourceType": "module" }, "extends": ["eslint:recommended", "prettier"], "env": { "browser": true, "node": true }, "rules": { "no-console": "error" }
}

The root property indicates that this configuration is the root of the project, because it is possible to use multiple ESLint configuration files.

The parserOptions defines what version of ECMAScript you use in your code and if you use modules or not ( import / export syntax).

The extends property allows to add rules to the configuration. Here I use the recommended rules of ESLint and the rules defined by the eslint-config-prettier package, that simply override conflicting rules between ESLint and Prettier. The order is important, most of the time you will want to have the prettier rules last.

The env property defines which kind of environment your code will run in, if it is a Node.js application then set node to true if it will run in a browser (like a React app for example) then set browser to true.

Finally the rules property allows you to add/edit rules specifically. I like to add the no-console: “error” rule so that ESLint throws an error when I use console.log. Of course, I still use console.log but only while working locally, I never commit code with console.log unless it is for real logging cases and not for debugging.

There are more options available, have a look at the official ESLint documentation if youre interested.

For Prettier, I like to use the default configuration, but they also have a configuration file (.prettierrc) if you wish to force a specific code style. If you’re interested, have a look at the official Prettier documentation.

Now lets add some scripts in the package.json so that we can run ESLint and Prettier manually

{ "scripts": { "format:check": "prettier --check .", "format:write": "prettier --write .", "lint:check": "eslint .", "lint:fix": "eslint --fix ." }
}

You can now check if the formatting matches Prettiers rules by using

npm run format:check

And you can force the formatting by using

npm run format:write

You can also lint your code with

npm run lint:check

and auto-fix errors (when possible) with

npm run lint:fix

Try the commands by creating a new JavaScript file and adding some badly formatted code in it. If youve added the no-console: “error” ESLint rule, you can easily check that ESLint is working correctly by adding a console.log in that JavaScript file.

// example.js
function example() { console.log("Hello World!"); }

Now lets see how to configure Visual Studio Code to lint your code automatically and format when you save. If you use a different IDE, they might also have plugins for ESLint and Prettier but you will need to check how to configure them.

You will need to install the two following extensions:

There is an extra step to activate them. We need to edit the Visual Studio Code settings. I like to do this per workspace but you can also edit the settings globally.

Lets create a .vscode directory in the project

mkdir .vscode

Then add a settings.json file inside that directory

touch .vscode/settings.json

Add the following inside the .vscode/settings.json file

{ "editor.formatOnSave": true, "files.autoSave": "onFocusChange", "editor.defaultFormatter": "esbenp.prettier-vscode", "editor.codeActionsOnSave": { "source.fixAll.eslint": true }
}

The “editor.formatOnSave”: true rule tells VSCode to run the code formatter (Prettier) when saving.

The “files.autoSave”: “onFocusChange” rule tells VSCode to automatically save when changing window or opening a new file (when the focus on the current file is lost)

The “editor.defaultFormatter”: “esbenp.prettier-vscode” rule tells VSCode to use the Prettier extension as the default code formatter.

The “editor.codeActionsOnSave” rule allows to define more actions to run when saving. In this case I added “source.fixAll.eslint”: true which will run ESLint with the –fix parameter to attempt to automatically fix the errors.

Of course it is up to you to edit these settings to your liking, these are just my personal preferences.

Finally lets see how to configure a pre-commit hook to automatically run ESLint and Prettier before committing your code.

A pre-commit hook is a Git feature that allows to run a command before doing a git commit. To set it up we will use the husky package. We will also use the lint-staged package, so that we only run ESLint and Prettier on files that will be committed. If you’re working on a big project it would be too slow to run ESLint and Prettier over the whole codebase.

You will need to install those two packages

npm install --save-dev husky lint-staged

Then, to enable the git hooks, use the following command

npx husky install

Run the following as well to make sure that Husky will be automatically setup when installing the dependencies (so that your teammates wont have to do all this)

npm set-script prepare "husky install"

And now lets create the pre-commit hook with the following command

npx husky add .husky/pre-commit "npx lint-staged"

Now, whenever you commit something, npx lint-staged will run before committing and if that command returns an error the commit will be cancelled.

This is useful if your teammates dont want to setup ESLint and Prettier in their IDE, at least they will be required to run them manually in order to commit.

We still need to configure lint-staged. Open the package.json and add the following

 "lint-staged": { "**/*.{js}": [ "eslint" ], "**/*.{js,json}": [ "prettier --check" ], }

Of course make sure to adapt this to target all the possible file extensions you use in your project.

Now, when lint-staged is executed (automatically thanks to the pre-commit hook), it will run ESLint then Prettier for all the matching files that have been staged (about to be committed).

Thats it, now you can focus on writing code and improving your code quality thanks to ESlint. You wont have to worry about formatting because Prettier will take care of it for you.

You can find the the full example on GitHub: https://github.com/ncribt/eslint-prettier-example

Discover more posts from me on my personal blog: https://naruhodo.dev

by NARUHODO @ncribt. Software engineer during the week and apprentice blogger during the weekend. I like JS and Rust. Read my stories

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.

Coinsmart. Beste Bitcoin-B繹rse in Europa
Source: https://hackernoon.com/how-to-code-better-with-eslint-and-prettier-configuration-nhr35uw?source=rss

Big Data

Image Classification using Convolutional Neural Network with Python

Published

on



Image Classification using CNN : Python Implementation – Analytics Vidhya





















Learn everything about Analytics


Coinsmart. Beste Bitcoin-B繹rse in Europa
Source: https://www.analyticsvidhya.com/blog/2021/06/image-classification-using-convolutional-neural-network-with-python/

Continue Reading

Big Data

Image Classification using Convolutional Neural Network with Python

Published

on



Image Classification using CNN : Python Implementation – Analytics Vidhya





















Learn everything about Analytics


Coinsmart. Beste Bitcoin-B繹rse in Europa
Source: https://www.analyticsvidhya.com/blog/2021/06/image-classification-using-convolutional-neural-network-with-python/

Continue Reading

ZDNET

Samsung to supply open RAN and 5G solutions to Vodafone UK

Published

on

Samsung said on Monday that is has been selected as a vendor of open RAN, 4G and 5G solutions to Vodafone for the telco’s virtualized RAN (vRAN) deployment in the UK.

The South Korean tech giant will supply its vRAN solutions and open RAN compliant radios such as its massive MIMO for both low-band and mid-band spectrum to the telco. 

This is the first time that Samsung is supplying its network kits to Vodafone, as well as its first to a large European mobile operator for 5G equipment. The company will also be the sole supplier of vRAN solutions. Other vendors for Vodafone’s rollout include Dell, NEC and Wind River.

Samsung said its vRAN solution is software based and runs on commercial off-the-shelf servers that offer features and performance that are level to that of traditional hardware equipment.

The company said the solution is cloud-native and has a container-based architecture that will offer flexible deployment and efficient network management for telcos.

According to Samsung, the vRAN’s architecture also has automation capabilities that simplify end-to-end network management. This will allow operators to quickly meet demands from new and existing services, with minimal impact on deployment, the company said.

“Vodafone is committed to leading the next wave of digital transformation across Europe, ensuring fast and reliable connectivity for all,” Vodafone CTO Johan Wibergh said.

“Open RAN, built on strong partnerships, is key to realizing this ambition. Samsung’s innovative solutions and expertise are part of the foundation that is creating this network of the future.”

Samsung Network president Kyungwhoon Cheun said: “This is a major step forward, as more operators are transitioning into new RAN technologies to prioritize user experience and efficiency.”

Samsung’s network business has been making inroads into major markets in recent years. In March, the company announced that it will be supplying its 5G kits to NTT Docomo, Japan’s largest mobile operator.

In September last year, Samsung said it will be supplying $6.6 billion worth of network equipment to US carrier Verizon.

Checkout PrimeXBT
Trade with the Official CFD Partners of AC Milan
Source: https://www.zdnet.com/article/samsung-to-supply-open-ran-and-5g-solutions-to-vodafone-uk/#ftag=RSSbaffb68

Continue Reading

Publications

How to Find The Stinky Parts of Your Code [Part XI]

Published

on

Maximiliano Contieri Hacker Noon profile picture

@mcseeMaximiliano Contieri

Im senior software engineer specialized in declarative designs and S.O.L.I.D. and Agile lover.

Yet more code smells? Aren’t them enough?

We see several symptoms and situations that make us doubt the quality of our development.

Let’s look at some possible solutions.

Most of these smells are just hints of something that might be wrong. They are not rigid rules.

This is part V. Part I can be found here, Part II here, Part III is here, Part IV herepart VVI, VII, VIII, IX and  the last one (for now).

Let’s continue…

Not operator is our friend. Not not operator is not our friend.

  • Readability
  1. Name your variables, methods and classes with positive names.

Wrong

if ( !work.isNotFinished() )

Right

if ( work.isDone() )

This is a semantic smell. We need to detect it on code reviews.

We can tell linters to check for Regular Expressions like !not or !isNot etc as a warning.

  • Readability

Double negation is a very basic rule we learn as junior developers.

There are lots of production systems filled with this smell.

We need to trust our test coverage and make safe renames and other refactors.

Photo by Daniel Herron on Unsplash

Its harder to read code than to write it.

Joel Spolsky

Tests are our safety nets. If we dont trust on their integrity, we will be in great danger.

  • Determinism
  • Confidence loss
  • Wasted time
  1. Test should be in full control. There should be no space for erratic behavior and degrees of freedom.
  2. Remove all tests coupling.

Fragile, Intermittent, Sporadic or Erratic tests are common in many organizations.

Nevertheless, they mine the developers trust.

We must avoid them.

Wrong

import static org.junit.Assert.assertEquals; import org.junit.Test; import components.set.Set;
import components.set.Set1L; public abstract class SetTest { protected abstract Set<String> constructor(); @Test public final void testAddEmpty() { Set<String> s = this.constructor(); s.add("green"); s.add("blue"); assertEquals("{green. blue}", s.toString()); //This is fragile since it dependes on set sort (which is not defined) } }

Right

import static org.junit.Assert.assertEquals; import org.junit.Test; import components.set.Set;
import components.set.Set1L; public abstract class SetTest { protected abstract Set<String> constructor(); @Test public final void testAddEmpty() { Set<String> s = this.constructor(); s.add("green"); assertEquals("{green}", s.toString()); } @Test public final void testEntryAtSingleEntry() { Set<String> s = this.createFromArgs("red"); Boolean x = s.contains("red"); assertEquals(true, x); } }

Detection can be done with test run statistics.

It is very hard to put some test in maintenance since we are removing a safety net.

  • Coupling
  • Determinism

Fragile tests show system coupling and not deterministic or erratic behavior.

Developers spend lots of time and effort fighting against this false positives.

The amateur software engineer is always in search of magic.

Grady Booch

We learned loops back in school. But enumerators and iterators are the next generation.

Photo by Elena Mozhvilo on Unsplash

  • Encapsulation.
  • Declarativeness.
  1. Favor foreach() or high order iterators
  2. You will be able to use yield(), caches, proxies, lazy loading and much more when you hide your implementation details.

Wrong

for (i = 0; i < colors.count(), i++) { print(colors[i]);
}

Right

foreach (color of colors) { print(color);
} //Closures and arrow functions
colors.foreach(color => print(color));

Linters can find this smell using regex.

There might be false positives. See exceptions below.

If the problem domain needs the elements to be bijected to natural numbers like indices, the first solution is adequate.

Remember all time to find real world analogies.

Tags

  • Declarative

This kind of smell do not ring the bell to many developers because they think this is a subtlety.

Clean code is full of this few declarative things that can make a difference.

If you get tired of writing for loops, take a break and continue later.

David Walker

Code is there. Just in case. We might need it soon.

Photo by Kris Mikael Krister on Unsplash

  • Complexity
  • Coupling
  1. Remove dead code.
  2. Leave covered and real tested code.

Wrong

<? final class DatabaseQueryOptimizer { public function selectWithCriteria($tableName, $criteria) { //Make some optimizations manipulating criterias } private function sqlParserOptimization(SQLSentence $sqlSentence): SQLSentence { //Parse the SQL converting it to an string and then working with their nodes as strings and lots of regex //This was a very costly operation overcoming real SQL benefits. //But since we made too much work we decide to keep the code.  } }

Right

<? final class DatabaseQueryOptimizer { public function selectWithCriteria($tableName, $criteria) { //Make some optimizations manipulating criterias } }

Using some mutation testing variants we can remove the dead code and see it test fails.

We need to have good coverage to rely on this solution.

Dead code is always a problem.

We can use modern development techniques like TDD to ensure all code is alive.

It is very hard to predict, especially the future.

Niels Bohr

If you see your objects as data holders you will violate their encapsulation, but you shouldnt, as in real life, you should always ask for consent.

Picture by Nicolas Poussin

  • Information Hiding Violation
  • Encapsulation Violation
  • Coupling
  1. Couple to interfaces and behavior, never data.

Wrong

<? final class Point { public $x; public $y;
} final class DistanceCalculator { function distanceBetween(Point $origin, Point $destination) { return sqrt((($destination->x - $origin->x) ^ 2) + (($destination->y - $origin->y) ^ 2)); }
}

Right

<? final class Point { private $rho; private $theta; public function x() { return $this->rho * cos($this->theta); } public function y() { return $this->rho * sin($this->theta); }
} final class DistanceCalculator { function distanceBetween(Point $origin, Point $destination) { return sqrt((($destination->x() - $origin->x() ^ 2) + (($destination->y() - $origin->y()) ^ 2))); } }

You can set your linters to warn you for public attributes, setters and getters usage and discourage them.

If your classes are polluted with setters, getters and public methods you will certainly have ways to couple to their accidental implementation.

  • Inappropriate intimacy

A data structure is just a stupid programming language.

Bill Gosper

We are done for now. But we are pretty sure we will come across even more smells very soon!

I keep getting more suggestions on twitter, so they won’t be the last!

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.

Coinsmart. Beste Bitcoin-B繹rse in Europa
Source: https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-xi-sit35t1?source=rss

Continue Reading
Esports5 days ago

Genshin Impact Echoing Conch Locations Guide

Esports5 days ago

MLB The Show 21 Kitchen Sink 2 Pack: Base Round Revealed

Aviation4 days ago

The Story Of The Boeing 777 Family

zephyrnet4 days ago

7th Global Blockchain Congress by Agora Group & TDeFi on June 21st and 22nd, 2021, Dubai.

Crowdfunding3 days ago

April/May 2021 Top Campaigns

Big Data4 days ago

.NET DEVELOPMENT

Blockchain4 days ago

Woonkly will be the official Title Sponsor of the 7th edition Global Blockchain Congress organized by Agora Group in Dubai

Blockchain4 days ago

Death Cross is Appearing Over Bitcoin Price Chart

Crowdfunding4 days ago

US Fintech Broadridge Partners with Amazon Web Services to Expand Private Market Hub, Leveraging DLT

Big Data4 days ago

China arrests over 1,100 suspects in crackdown on crypto-related money laundering

Blockchain3 days ago

Crypto Fund Manager Says Bitcoin ETFs to be Approved By 2022

Gaming4 days ago

TrustDice Review: Features & Promotions

Esports4 days ago

Every new Passive Power in Legends of Runeterra Lab of Legends 2.9.0

Cleantech4 days ago

TC Energy Cancels Keystone XL Pipeline

Fintech3 days ago

PayPal launches PayPal Rewards Card in Australia

Cyber Security2 days ago

Data Breach that Impacted Both Audi of America and Volkswagen of America

Energy2 days ago

Industrial robots market in the automotive industry | $ 3.97 billion growth expected during 2021-2025 | 17000+ Technavio Research Reports

Energy2 days ago

Daiki Axis Co., Ltd. (4245, First Section, Tokyo Stock Exchange) Overview of Operating Performance for the First Three Months Ended March 31, 2021

Esports2 days ago

Lost Ark Founders Pack: Everything You Need to Know

Cleantech2 days ago

Tesla Model S 420 Plaid Is The Best Car In The World (But Not For Me)

Trending