Javascript Style Guide

From Proxmox VE
Jump to: navigation, search

Proxmox Javascript Style Guide

Various of our files have inconsistent styles due to historical growth as well as because of the mixed styles we got from various contributors.

Please try to follow this guide if you're working on code for Proxmox projects to avoid adding to the style mess.

Here's a summary of our style (which is somewhat unusual at least when it comes to the mixed indentation).

Indentation

We indent by 4 spaces, assume tabs to be 8 spaces and convert all groups of 8 spaces into tabs at the beginning of a line. Here's an example, with tabs represented via '>........'

function foo(arg1, arg2, arg3) {
    if (arg1) {
>.......console.log(arg2);
>.......if (arg3) {
>.......    if (arg3 !== arg2) {
>.......>.......throw "Exceptions should avoided for dynamic stuff";
>.......    }
>.......}
    }
}

Like all editors for some reason I'll never understand we do not distinguish between indentation and alignment, so if you split up an expression over multiple lines we still use the same "all 8 spaces are 1 tab" pattern.

The vim configuration would be :set ts=8 sts=4 sw=4 noet

Breaking long lines and strings

The preferred limit on the length of a single line is 80 columns.

Statements longer than 80 columns should be broken into sensible chunks, unless exceeding 80 columns significantly increases readability and does not hide information. The maximal line length tolerated for those exceptions is 100 columns.

The vim configuration would be :set cc=81 or, to show both soft and hard limit: :set cc=81,101

Linting

Instead of describing various rules and examples to follow the used coding and formatting style, it's quicker to just use eslint.

Installation

We provide an ESLint wrapper with our desired rule set backed in as default. You can install it easily after setting up the 'devel' package repository:

apt update
apt install pve-eslint

Basic Usage

Check specific files:

eslint src/Utils.js

Check all .js files from this and child directories:

eslint .

A great deal of errors or warnings can be automatically fixed:

eslint --fix .

Rule Information

For errors and warnings ESLint will show a shorter rule ID and a longer human-readable string.

You can use the rule ID to search the ESLint documentation, to get more information about a specific rule: https://eslint.org/docs/rules/