Skip to content

Commit 6ac10bd

Browse files
committed
js-style-guide update
1 parent 0639f05 commit 6ac10bd

1 file changed

Lines changed: 59 additions & 55 deletions

File tree

  • website/docs/developer/js-style-guide

website/docs/developer/js-style-guide/index.mdx

Lines changed: 59 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
11
---
22

3-
title: JavaScript Style Guide
4-
description: For consistency, use the Standard JS/TS validation tools.
3+
title: JavaScript/TypeScript Style Guide
4+
description: For consistency, use automated validation tools (prettier & ESlint).
55
keywords:
66
- xpack
77
- javascript
8+
- typescript
89
- style
910
- guide
1011

1112
date: 2017-10-09 02:47:00 +0300
1213

1314
---
1415

15-
# JavaScript Style Guide
16+
# JavaScript -> TypeScript Style Guide
1617

1718
:::info
1819

@@ -29,16 +30,18 @@ the conclusion is that the specific style is of lesser importance;
2930
what matters more is its consistent application.
3031

3132
To ensure consistency in the xPack JavaScript source files, the
32-
primary requirement is to pass the [Standard JS](https://standardjs.com)
33-
validation tools, which also have a TypeScript variant
34-
([ts-standard](https://www.npmjs.com/package/ts-standard)).
33+
primary requirements are:
34+
35+
- use [prettier](https://prettier.io) for automated re-formatting
36+
- use [ESlint](https://eslint.org) as a validation tool, which also
37+
has a TypeScript variant
38+
([typescript-eslint](https://typescript-eslint.io/packages/typescript-eslint/))
3539

3640
Following this, the main recommendations are:
3741

38-
- Utilise the ECMAScript 6 specifications (ES 6).
39-
- If the module performs reasonably complex tasks, its public functions **must be asynchronous**.
40-
- Asynchronous functions should **use promises** (and definitely **avoid callbacks**).
41-
- **Reentrancy** should be carefully considered (avoid module-global variables).
42+
- utilise the ECMAScript 6 specifications (ES 6)
43+
- asynchronous functions should **use promises** (and definitely **avoid callbacks**)
44+
- **reentrancy** should be carefully considered (avoid module-global variables)
4245

4346
## The xPack Project preferences
4447

@@ -53,8 +56,8 @@ Definitely **avoid using old-style code**.
5356
### Use classes as much as possible
5457

5558
Even if the new syntax is mostly syntactic sugar, and internally things
56-
behave as strangely as they did in the first JavaScript versions,
57-
still **use the new class syntax** at large; it is much cleaner and
59+
behave as they did in the first JavaScript versions,
60+
still **use the new class syntax** extensively; it is much cleaner and
5861
improves readability.
5962

6063
### Use promises instead of callbacks
@@ -83,15 +86,17 @@ make the module **export a class, and create instances of it**
8386
whenever needed; for sharing data between instances,
8487
**use static class members**.
8588

86-
### Do not restrict export to a single function or class
89+
### Do not restrict exports to a single function or class
8790

8891
Bad style:
8992

9093
```js
9194
module.exports = function () {
9295
return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;
9396
};
94-
...
97+
```
98+
99+
```js
95100
const func = require('name')
96101
```
97102

@@ -100,17 +105,21 @@ extensions, for example exporting a second function from the same module
100105
would mandate all modules that use the first function via `require()` to
101106
be updated to `require().func1`, which may cause many headaches to developers.
102107

108+
Recommended style:
109+
103110
```js
104-
module.exports.func1 = function () {
105-
return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;
106-
};
107-
module.exports.func2 = function () { ... }
108-
...
109-
const { func1 } = require('name')
111+
export function func1 () {
112+
return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g
113+
}
114+
export function func2 () { ... }
110115
```
111116

112-
The recommendation is to always return functions or preferably classes
113-
as properties of the `module.exports` object, and get them individually by name.
117+
```js
118+
import { func1, func2 } from 'name'
119+
```
120+
121+
The recommendation is to always export functions or preferably classes
122+
and get them individually by name.
114123

115124
### Prefer static classes to group methods
116125

@@ -119,26 +128,26 @@ functionality) either below a parent object, or, even better, in
119128
classes with static members.
120129

121130
The main advantage of this scheme is that adding new exports will
122-
only change the interface incrementally, minimising the risk to
123-
break backward compatibility.
131+
only change the interface incrementally, minimising the risk of
132+
breaking backward compatibility.
124133

125134
### Use the spread operator
126135

127-
Th spread operator expands an iterable into its member objects. It also works
136+
The spread operator expands an iterable into its member objects. It also works
128137
with arrays and objects
129138

130139
- Create array copies
131140

132141
```js
133-
const arr1 = [1, 2 3]
142+
const arr1 = [1, 2, 3]
134143
const arr2 = [...arr1]
135144
```
136145

137146
- Concatenate arrays
138147

139148
```js
140-
const arr1 = [1, 2 3]
141-
const arr2 = [4, 5 6]
149+
const arr1 = [1, 2, 3]
150+
const arr2 = [4, 5, 6]
142151
const arr3 = [...arr1, ...arr2]
143152
```
144153

@@ -152,7 +161,8 @@ class Base {
152161
parent: null,
153162
...args
154163
})
155-
// ...
164+
// ...
165+
}
156166
}
157167
```
158168

@@ -170,7 +180,7 @@ iterable.forEach((value) => {
170180

171181
Debug note: Visual Studio Code is able to step into the lambda function.
172182

173-
For more complex loops, use `for ... of`.
183+
For more complex loops, use `for ... of` (not `in`!).
174184

175185
```js
176186
let iterable = [10, 20, 30]
@@ -266,9 +276,9 @@ Please note that `null` is also an object, and everything created with
266276
### Use Map to guarantee the order of the values
267277

268278
Although maps can be conveniently implemented with regular objects,
269-
the specs do not guarantee the insert order to be preserved.
279+
the specifications do not guarantee the insert order to be preserved.
270280

271-
If the order is important, or if the object need to store other
281+
If the order is important, or if the object needs to store other
272282
properties too, use a `Map`.
273283

274284
### Make node exports/imports look like ES6 exports/imports
@@ -561,7 +571,7 @@ Use single quotes for strings except to avoid escaping
561571
```js
562572
const ok = 'String contains "double" quotes'
563573
const alsoOk = "String contains 'single' quotes or apostrophe"
564-
const paramOk = `Back quotes string with ${parameter}`
574+
const paramOk = `Back-quoted string with ${parameter}`
565575
```
566576

567577
### White spaces
@@ -592,9 +602,9 @@ Use named functions.
592602

593603
### Exceptions
594604

595-
For the native Node.js callback usage, never to ever ever throw anything. It's worse than useless. Just send the error message back as the first argument to the callback.
605+
For the native Node.js callback usage, throwing anything is worse than useless. Simply send the error message back as the first argument to the callback.
596606

597-
But for the modern ES 6 promise usage, exceptions are fine.
607+
However, for the modern ES 6 promise usage, exceptions are acceptable.
598608

599609
## From [Node.js modules](https://nodejs.org/dist/latest-v6.x/docs/api/modules.html)
600610

@@ -610,19 +620,19 @@ Modules are cached after the first time they are loaded. This means (among other
610620

611621
From this point of view, modules behave like [singletons](https://en.wikipedia.org/wiki/Singleton_pattern); they can also be compared to static classes in C++.
612622

613-
Leaving status at the module level can be either a blessing or a curse, depending on the environment used to run the module. In server environments, using module-global variables is like using static variables in a multi-threaded environment, if not handled correctly it may have unexpected results.
623+
Leaving state at the module level can be either a blessing or a curse, depending on the environment used to run the module. In server environments, using module-global variables is like using static variables in a multi-threaded environment; if not handled correctly, it may have unexpected results.
614624

615625
### Exports
616626

617-
To make some functions and objects visible outside the module, you can add them as properties to the special `modules.exports` object:
627+
To make some functions and objects visible outside the module, add them as properties to the special `module.exports` object:
618628

619629
```js
620630
const PI = Math.PI
621631
module.exports.area = (r) => PI * r * r
622632
module.exports.circumference = (r) => 2 * PI * r
623633
```
624634

625-
Although you can rewrite the `module.export` to be a single function (such as a constructor), still prefer to add them as properties to the object and refer to them explicitly in the `require()` line:
635+
Although you can rewrite the `module.exports` to be a single function (such as a constructor), it is still preferable to add them as properties to the object and refer to them explicitly in the `require()` line:
626636

627637
```js
628638
const square = require('./square.js').square
@@ -646,24 +656,24 @@ When a file is run directly from Node.js, `require.main` is set to its module. T
646656
require.main === module
647657
```
648658

649-
### The module wrapper
659+
### The module wrapper (deprecated by ES6)
650660

651661
Before a module's code is executed, Node.js will wrap it with a function wrapper that looks like the following:
652662

653663
```js
654664
module = ... // an object for the current module
655-
module.export = {} // an empty object
656-
exports = module.export // a reference to the exports; avoid using it
665+
module.exports = {} // an empty object
666+
exports = module.exports // a reference to the exports; avoid using it
657667
__filename = '/x/y/z/abc.js'
658668
__dirname = '/x/y/z'
659669
(function (exports, require, module, __filename, __dirname) {
660-
// Your module code actually lives in here
670+
// The module code actually lives in here
661671
});
662672
```
663673

664-
In each module, the `module` variable is a reference to the object representing the current module. `module` isn't actually a global but rather local to each module.
674+
In each module, the `module` variable is a reference to the object representing the current module. `module` is not actually a global but rather local to each module.
665675

666-
The `module.exports` object is created by the Module system. Sometimes this is not acceptable; many want their module to be an object of their own. To do this, assign the desired export object to `module.exports`.
676+
The `module.exports` object is created by the Module system. Sometimes this is not acceptable; many developers want their module to be an object of their own. To do this, assign the desired export object to `module.exports`.
667677

668678
For convenience, `module.exports` is also accessible via the `exports` module-global. Note that assigning a value to `exports` will simply rebind the local exports variable, which is probably not what you want to do; if the relationship between `exports` and `module.exports` seems like magic to you, ignore `exports` and only use `module.exports`.
669679

@@ -726,14 +736,13 @@ var chars = [...str];
726736
console.log(chars);
727737
```
728738

739+
## Reformatting and Validation Tools
729740

730-
## Links to other style guides
731-
732-
Preferred:
741+
- [prettier](https://prettier.io)
742+
- [ESLint](https://eslint.org)
743+
- [typescript-eslint](https://typescript-eslint.io/packages/typescript-eslint)
733744

734-
- [JavaScript "Standard" Style](https://standardjs.com)
735-
736-
Other links:
745+
## Links to other style guides
737746

738747
- [10 Best JavaScript Style Guides](https://noeticforce.com/best-javascript-style-guide-for-maintainable-code)
739748
- [airbnb JavaScript Style Guide](https://github.com/airbnb/javascript)
@@ -744,11 +753,6 @@ Other links:
744753
- [RisingStack/node-style-guide](https://github.com/RisingStack/node-style-guide)
745754
- [kettanaito/naming-cheatsheet](https://github.com/kettanaito/naming-cheatsheet)
746755

747-
## Linting Tools
748-
749-
Preferred (used automatically by Standard):
750-
751-
- [ESLint](https://eslint.org/), but indirectly via the 'Standard JS' tools.
752756

753757
Other links:
754758

0 commit comments

Comments
 (0)