Standardizing the code style in a Node.js project

Oct 31, 2018 - 2 min read

Using tools to automate the coding style frees up mental resources for other tasks. How about never arguing over where the braces go, should there be a space after the function name, or tabs vs. spaces? View source code at GitHub or download zipped master.

Following tools help achieve this goal:

  • ESLint - Static analysis tool to find problematic patterns of code
  • Prettier - An opinionated code formatter (integrates with ESLint)
  • EditorConfig - Maintain consistent line endings, indentation, etc. across editors and files

Install required packages

Use the following command to install all required dev dependencies:

npm i -D -E eslint prettier eslint-config-prettier eslint-plugin-prettier

Tip: Using the -E (--save-exact) flag we ensure that packages are never updated automatically, only manually. This will prevent unexpected issues popping up, for example when new rules are added to Prettier but the code does not conform to them yet.

ESLint and Prettier

To configure ESLint to run and use Prettier, create a file called .eslintrc in root directory of the project:

{
  "env": { "node": true },                    // Take Node.js global variables into consideration
  "parserOptions": { "ecmaVersion": 2017 },   // Lint with this version in mind
  "extends": ["plugin:prettier/recommended"]  // Override ESLint rules with Prettier and use Prettier formatter
}

Tip: Search for plugins for your favorite IDE for better integration (eg. VSCode has ESLint and Prettier plugins)

Adding the lint command

To easily lint your code and uncover various issues, edit the package.json and add the lint command to the "scripts" section. This example assumes your code is located in the src/ directory in the root of the project.

"scripts": {
  ...
  "lint": "eslint src/",
  ...
},

Tip: Run the command with npm run lint

EditorConfig

To consolidate the charset, line endings, indentation, etc. create an editor configuration file .editorconfig in the project root directory:

root = true

[*]
charset = utf-8
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf
indent_style = space
indent_size = 2

Note: Some editors read this file automatically, and some require plugins. For example, Visual Studio will read this file, and Visual Studio Code requires the EditorConfig plugin. Check if you favorite IDE has a plugin for it.