diff --git a/.gitignore b/.gitignore
index 3c3629e647..386f24a0a4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,3 @@
node_modules
+yarn.lock
+package-lock.json
\ No newline at end of file
diff --git a/.npmrc b/.npmrc
new file mode 100644
index 0000000000..32fd3a789f
--- /dev/null
+++ b/.npmrc
@@ -0,0 +1 @@
+git-tag-version=false
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000000..d5dcbb48b7
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,11 @@
+language: node_js
+node_js: node
+
+install: npm install
+
+cache:
+ directories:
+ - node_modules
+
+notifications:
+ email: false
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000..c8b3e33011
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2018 by all contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
index fdcdccae2b..e97a0d06ae 100644
--- a/README.md
+++ b/README.md
@@ -1,15 +1,24 @@
-# Airbnb JavaScript Style Guide() {
+# BigchainDB JavaScript Style Guide
-*A mostly reasonable approach to JavaScript*
+For consistent JavaScript across BigchainDB-related repos.
-[](https://www.npmjs.com/package/eslint-config-airbnb)
-[](https://gitter.im/airbnb/javascript?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
+[](https://travis-ci.org/ascribe/javascript)
+[](https://greenkeeper.io/)
+[](https://github.com/ascribe/javascript)
-Other Style Guides
- - [ES5](es5/)
- - [React](react/)
- - [CSS & Sass](https://github.com/airbnb/css)
- - [Ruby](https://github.com/airbnb/ruby)
+## Introduction
+
+At ascribe we write a lot of JavaScript and value quality code. Since all of us liked [Airbnb's JavaScript Style Guide](https://github.com/airbnb/javascript), we figured that we can just fork it and change it to our needs.
+
+- [JavaScript Style Guide (this document)](#table-of-contents)
+- [React Style Guide](react/)
+
+## Usage
+
+Use the provided ESlint packages under `packages/` and refer to their documentation for detailed usage:
+
+- [](https://www.npmjs.com/package/eslint-config-ascribe) [eslint-config-ascribe](packages/eslint-config-ascribe)
+- [](https://www.npmjs.com/package/eslint-config-ascribe-react) [eslint-config-ascribe-react](packages/eslint-config-ascribe-react)
## Table of Contents
@@ -44,9 +53,6 @@ Other Style Guides
1. [Performance](#performance)
1. [Resources](#resources)
1. [In the Wild](#in-the-wild)
- 1. [Translation](#translation)
- 1. [The JavaScript Style Guide Guide](#the-javascript-style-guide-guide)
- 1. [Chat With Us About JavaScript](#chat-with-us-about-javascript)
1. [Contributors](#contributors)
1. [License](#license)
@@ -89,7 +95,7 @@ Other Style Guides
- [2.1](#2.1) Use `const` for all of your references; avoid using `var`.
- > Why? This ensures that you can't reassign your references (mutation), which can lead to bugs and difficult to comprehend code.
+ > Why? This ensures that you can't reassign your references (mutation), which can lead to bugs and difficult to comprehend code.
```javascript
// bad
@@ -103,19 +109,19 @@ Other Style Guides
- [2.2](#2.2) If you must mutate references, use `let` instead of `var`.
- > Why? `let` is block-scoped rather than function-scoped like `var`.
+ > Why? `let` is block-scoped rather than function-scoped like `var`.
```javascript
// bad
var count = 1;
if (true) {
- count += 1;
+ count += 1;
}
// good, use the let.
let count = 1;
if (true) {
- count += 1;
+ count += 1;
}
```
@@ -124,8 +130,8 @@ Other Style Guides
```javascript
// const and let only exist in the blocks they are defined in.
{
- let a = 1;
- const b = 1;
+ let a = 1;
+ const b = 1;
}
console.log(a); // ReferenceError
console.log(b); // ReferenceError
@@ -150,14 +156,14 @@ Other Style Guides
```javascript
// bad
const superman = {
- default: { clark: 'kent' },
- private: true,
+ default: { clark: 'kent' },
+ private: true,
};
// good
const superman = {
- defaults: { clark: 'kent' },
- hidden: true,
+ defaults: { clark: 'kent' },
+ hidden: true,
};
```
@@ -166,43 +172,43 @@ Other Style Guides
```javascript
// bad
const superman = {
- class: 'alien',
+ class: 'alien',
};
// bad
const superman = {
- klass: 'alien',
+ klass: 'alien',
};
// good
const superman = {
- type: 'alien',
+ type: 'alien',
};
```
- [3.4](#3.4) Use computed property names when creating objects with dynamic property names.
- > Why? They allow you to define all the properties of an object in one place.
+ > Why? They allow you to define all the properties of an object in one place.
```javascript
function getKey(k) {
- return `a key named ${k}`;
+ return `a key named ${k}`;
}
// bad
const obj = {
- id: 5,
- name: 'San Francisco',
+ id: 5,
+ name: 'Berlin',
};
obj[getKey('enabled')] = true;
// good
const obj = {
- id: 5,
- name: 'San Francisco',
- [getKey('enabled')]: true,
+ id: 5,
+ name: 'Berlin',
+ [getKey('enabled')]: true,
};
```
@@ -212,45 +218,45 @@ Other Style Guides
```javascript
// bad
const atom = {
- value: 1,
+ value: 1,
- addValue: function (value) {
- return atom.value + value;
- },
+ addValue: function (value) {
+ return atom.value + value;
+ },
};
// good
const atom = {
- value: 1,
+ value: 1,
- addValue(value) {
- return atom.value + value;
- },
+ addValue(value) {
+ return atom.value + value;
+ },
};
```
- [3.6](#3.6) Use property value shorthand.
- > Why? It is shorter to write and descriptive.
+ > Why? It is shorter to write and descriptive.
```javascript
const lukeSkywalker = 'Luke Skywalker';
// bad
const obj = {
- lukeSkywalker: lukeSkywalker,
+ lukeSkywalker: lukeSkywalker,
};
// good
const obj = {
- lukeSkywalker,
+ lukeSkywalker,
};
```
- [3.7](#3.7) Group your shorthand properties at the beginning of your object declaration.
- > Why? It's easier to tell which properties are using the shorthand.
+ > Why? It's easier to tell which properties are using the shorthand.
```javascript
const anakinSkywalker = 'Anakin Skywalker';
@@ -258,22 +264,49 @@ Other Style Guides
// bad
const obj = {
- episodeOne: 1,
- twoJediWalkIntoACantina: 2,
- lukeSkywalker,
- episodeThree: 3,
- mayTheFourth: 4,
- anakinSkywalker,
+ episodeOne: 1,
+ twoJediWalkIntoACantina: 2,
+ lukeSkywalker,
+ episodeThree: 3,
+ mayTheFourth: 4,
+ anakinSkywalker,
};
// good
const obj = {
- lukeSkywalker,
- anakinSkywalker,
- episodeOne: 1,
- twoJediWalkIntoACantina: 2,
- episodeThree: 3,
- mayTheFourth: 4,
+ lukeSkywalker,
+ anakinSkywalker,
+ episodeOne: 1,
+ twoJediWalkIntoACantina: 2,
+ episodeThree: 3,
+ mayTheFourth: 4,
+ };
+ ```
+
+ - [3.8](#3.8) Prefer quoting only properties that are invalid identifiers, but always ensure that all properties are consistently quoted.
+
+ > Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many javascript engines.
+
+ ```javascript
+ // bad
+ const bad = {
+ foo: 3,
+ bar: 4,
+ 'data-blah': 5
+ };
+
+ // good
+ const good = {
+ 'foo': 3,
+ 'bar': 4,
+ 'data-blah': 5
+ };
+
+ // better
+ const better = {
+ foo: 3,
+ bar: 4,
+ dataBlah: 5
};
```
@@ -313,7 +346,7 @@ Other Style Guides
let i;
for (i = 0; i < len; i++) {
- itemsCopy[i] = items[i];
+ itemsCopy[i] = items[i];
}
// good
@@ -332,30 +365,55 @@ Other Style Guides
- [5.1](#5.1) Use object destructuring when accessing and using multiple properties of an object.
- > Why? Destructuring saves you from creating temporary references for those properties.
+ > Why? Destructuring saves you from creating temporary references for those properties.
```javascript
// bad
function getFullName(user) {
- const firstName = user.firstName;
- const lastName = user.lastName;
+ const firstName = user.firstName;
+ const lastName = user.lastName;
- return `${firstName} ${lastName}`;
+ return `${firstName} ${lastName}`;
}
// good
function getFullName(obj) {
- const { firstName, lastName } = obj;
- return `${firstName} ${lastName}`;
+ const { firstName, lastName } = obj;
+ return `${firstName} ${lastName}`;
}
// best
function getFullName({ firstName, lastName }) {
- return `${firstName} ${lastName}`;
+ return `${firstName} ${lastName}`;
}
```
- - [5.2](#5.2) Use array destructuring.
+ - [5.2](#5.2) When destructuring requires multiple lines, follow formatting rules for [objects](#3.1):
+
+ ```javascript
+ // bad
+ const { first: {
+ nested
+ },
+ second } = obj;
+
+ // bad
+ const {
+ first: {
+ nested
+ },
+ second } = obj;
+
+ // good
+ const {
+ first: {
+ nested
+ },
+ second
+ } = obj;
+ ```
+
+ - [5.3](#5.3) Use array destructuring.
```javascript
const arr = [1, 2, 3, 4];
@@ -368,15 +426,15 @@ Other Style Guides
const [first, second] = arr;
```
- - [5.3](#5.3) Use object destructuring for multiple return values, not array destructuring.
+ - [5.4](#5.4) Use object destructuring for multiple return values, not array destructuring.
- > Why? You can add new properties over time or change the order of things without breaking call sites.
+ > Why? You can add new properties over time or change the order of things without breaking call sites.
```javascript
// bad
function processInput(input) {
- // then a miracle occurs
- return [left, right, top, bottom];
+ // then a miracle occurs
+ return [left, right, top, bottom];
}
// the caller needs to think about the order of return data
@@ -384,14 +442,25 @@ Other Style Guides
// good
function processInput(input) {
- // then a miracle occurs
- return { left, right, top, bottom };
+ // then a miracle occurs
+ return { left, right, top, bottom };
}
// the caller selects only the data they need
const { left, right } = processInput(input);
```
+ - [5.5](#5.5) You can use destructuring and an object spread operator to filter out specific properties while keeping the other properties in a new object.
+
+ ```javascript
+ // bad
+ const val = obj.value;
+ delete obj.value;
+
+ // good
+ const { value: val, ...otherObj } = obj;
+ // otherObj will hold all other properties of obj except for value
+ ```
**[⬆ back to top](#table-of-contents)**
@@ -407,8 +476,23 @@ Other Style Guides
const name = 'Capt. Janeway';
```
- - [6.2](#6.2) Strings longer than 100 characters should be written across multiple lines using string concatenation.
- - [6.3](#6.3) Note: If overused, long strings with concatenation could impact performance. [jsPerf](http://jsperf.com/ya-string-concat) & [Discussion](https://github.com/airbnb/javascript/issues/40).
+ - [6.2](#6.2) When using (single- or double) quotes in a string, use the other literal (`''` or `""`).
+
+ ```javascript
+ // bad
+ const name = "What a \"nice\" day!";
+
+ // bad
+ const name = 'Let\'s go to Rosi\'s!';
+
+ // good
+ const name = 'What a "nice" day!';
+
+ // good
+ const name = "Let's go to Rosi's!";
+ ```
+
+ - [6.3](#6.3) Strings longer than 100 characters should be written across multiple lines using string concatenation.
```javascript
// bad
@@ -422,41 +506,43 @@ Other Style Guides
// good
const errorMessage = 'This is a super long error that was thrown because ' +
- 'of Batman. When you stop to think about how Batman had anything to do ' +
- 'with this, you would get nowhere fast.';
+ 'of Batman. When you stop to think about how Batman had anything to do ' +
+ 'with this, you would get nowhere fast.';
```
+ - [6.4](#6.4) Note: If overused, long strings with concatenation could impact performance. [jsPerf](http://jsperf.com/ya-string-concat) & [Discussion](https://github.com/airbnb/javascript/issues/40).
+
- - [6.4](#6.4) When programmatically building up strings, use template strings instead of concatenation.
+ - [6.5](#6.5) When programmatically building up strings, use template strings instead of concatenation.
- > Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation features.
+ > Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation features.
```javascript
// bad
function sayHi(name) {
- return 'How are you, ' + name + '?';
+ return 'How are you, ' + name + '?';
}
// bad
function sayHi(name) {
- return ['How are you, ', name, '?'].join();
+ return ['How are you, ', name, '?'].join();
}
// good
function sayHi(name) {
- return `How are you, ${name}?`;
+ return `How are you, ${name}?`;
}
```
- - [6.5](#6.5) Never use eval() on a string, it opens too many vulnerabilities.
-**[⬆ back to top](#table-of-contents)**
+ - [6.6](#6.6) **NEVER** use eval() on a string, it opens too many vulnerabilities.
+**[⬆ back to top](#table-of-contents)**
## Functions
- [7.1](#7.1) Use function declarations instead of function expressions.
- > Why? Function declarations are named, so they're easier to identify in call stacks. Also, the whole body of a function declaration is hoisted, whereas only the reference of a function expression is hoisted. This rule makes it possible to always use [Arrow Functions](#arrow-functions) in place of function expressions.
+ > Why? Function declarations are named, so they're easier to identify in call stacks. Also, the whole body of a function declaration is hoisted, whereas only the reference of a function expression is hoisted. This rule makes it possible to always use [Arrow Functions](#arrow-functions) in place of function expressions.
```javascript
// bad
@@ -468,64 +554,64 @@ Other Style Guides
}
```
- - [7.2](#7.2) Function expressions:
+ - [7.2](#7.2) Immediately-invoked function expressions should use arrow functions as opposed to traditional functions:
```javascript
// immediately-invoked function expression (IIFE)
(() => {
- console.log('Welcome to the Internet. Please follow me.');
+ console.log('Welcome to the Internet. Please follow me.');
})();
```
- - [7.3](#7.3) Never declare a function in a non-function block (if, while, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears.
+ - [7.3](#7.3) **NEVER** declare a function in a non-function block (if, while, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears.
- [7.4](#7.4) **Note:** ECMA-262 defines a `block` as a list of statements. A function declaration is not a statement. [Read ECMA-262's note on this issue](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf#page=97).
```javascript
// bad
if (currentUser) {
- function test() {
- console.log('Nope.');
- }
+ function test() {
+ console.log('Nope.');
+ }
}
// good
let test;
if (currentUser) {
- test = () => {
- console.log('Yup.');
- };
+ test = () => {
+ console.log('Yup.');
+ };
}
```
- - [7.5](#7.5) Never name a parameter `arguments`. This will take precedence over the `arguments` object that is given to every function scope.
+ - [7.5](#7.5) **NEVER** name a parameter `arguments`. This will take precedence over the `arguments` object that is given to every function scope.
```javascript
// bad
function nope(name, options, arguments) {
- // ...stuff...
+ // ...stuff...
}
// good
function yup(name, options, args) {
- // ...stuff...
+ // ...stuff...
}
```
- - [7.6](#7.6) Never use `arguments`, opt to use rest syntax `...` instead.
+ - [7.6](#7.6) **NEVER** use `arguments`, opt to use rest syntax `...` instead.
- > Why? `...` is explicit about which arguments you want pulled. Plus rest arguments are a real Array and not Array-like like `arguments`.
+ > Why? `...` is explicit about which arguments you want pulled. Plus rest arguments are a real Array and not Array-like like `arguments`.
```javascript
// bad
function concatenateAll() {
- const args = Array.prototype.slice.call(arguments);
- return args.join('');
+ const args = Array.prototype.slice.call(arguments);
+ return args.join('');
}
// good
function concatenateAll(...args) {
- return args.join('');
+ return args.join('');
}
```
@@ -535,68 +621,68 @@ Other Style Guides
```javascript
// really bad
function handleThings(opts) {
- // No! We shouldn't mutate function arguments.
- // Double bad: if opts is falsy it'll be set to an object which may
- // be what you want but it can introduce subtle bugs.
- opts = opts || {};
- // ...
+ // No! We shouldn't mutate function arguments.
+ // Double bad: if opts is falsy it'll be set to an object which may
+ // be what you want but it can introduce subtle bugs.
+ opts = opts || {};
+ // ...
}
// still bad
function handleThings(opts) {
- if (opts === void 0) {
- opts = {};
- }
- // ...
+ if (opts === void 0) {
+ opts = {};
+ }
+ // ...
}
// good
function handleThings(opts = {}) {
- // ...
+ // ...
}
```
- [7.8](#7.8) Avoid side effects with default parameters.
- > Why? They are confusing to reason about.
+ > Why? They are confusing to reason about.
- ```javascript
- var b = 1;
- // bad
- function count(a = b++) {
- console.log(a);
- }
- count(); // 1
- count(); // 2
- count(3); // 3
- count(); // 3
- ```
+ ```javascript
+ var b = 1;
+ // bad
+ function count(a = b++) {
+ console.log(a);
+ }
+ count(); // 1
+ count(); // 2
+ count(3); // 3
+ count(); // 3
+ ```
- [7.9](#7.9) Always put default parameters last.
```javascript
// bad
function handleThings(opts = {}, name) {
- // ...
+ // ...
}
// good
function handleThings(name, opts = {}) {
- // ...
+ // ...
}
```
-- [7.10](#7.10) Never use the Function constructor to create a new function.
+ - [7.10](#7.10) **NEVER** use the Function constructor to create a new function.
- > Why? Creating a function in this way evaluates a string similarly to eval(), which opens vulnerabilities.
+ > Why? Creating a function in this way evaluates a string similarly to eval(), which opens vulnerabilities.
- ```javascript
- // bad
- var add = new Function('a', 'b', 'return a + b');
+ ```javascript
+ // bad
+ var add = new Function('a', 'b', 'return a + b');
- // still bad
- var subtract = Function('a', 'b', 'return a - b');
- ```
+ // still bad
+ var subtract = Function('a', 'b', 'return a - b');
+ ```
**[⬆ back to top](#table-of-contents)**
@@ -604,29 +690,29 @@ Other Style Guides
- [8.1](#8.1) When you must use function expressions (as when passing an anonymous function), use arrow function notation.
- > Why? It creates a version of the function that executes in the context of `this`, which is usually what you want, and is a more concise syntax.
+ > Why? It creates a version of the function that executes in the context of `this`, which is usually what you want, and is a more concise syntax.
- > Why not? If you have a fairly complicated function, you might move that logic out into its own function declaration.
+ > Why not? If you have a fairly complicated function, you might move that logic out into its own function declaration.
```javascript
// bad
[1, 2, 3].map(function (x) {
- const y = x + 1;
- return x * y;
+ const y = x + 1;
+ return x * y;
});
// good
[1, 2, 3].map((x) => {
- const y = x + 1;
- return x * y;
+ const y = x + 1;
+ return x * y;
});
```
- [8.2](#8.2) If the function body consists of a single expression, feel free to omit the braces and use the implicit return. Otherwise use a `return` statement.
- > Why? Syntactic sugar. It reads well when multiple functions are chained together.
+ > Why? Syntactic sugar. It reads well when multiple functions are chained together.
- > Why not? If you plan on returning an object.
+ > Why not? If you plan on returning an object.
```javascript
// good
@@ -634,41 +720,41 @@ Other Style Guides
// bad
[1, 2, 3].map(number => {
- const nextNumber = number + 1;
- `A string containing the ${nextNumber}.`;
+ const nextNumber = number + 1;
+ `A string containing the ${nextNumber}.`;
});
// good
[1, 2, 3].map(number => {
- const nextNumber = number + 1;
- return `A string containing the ${nextNumber}.`;
+ const nextNumber = number + 1;
+ return `A string containing the ${nextNumber}.`;
});
```
- [8.3](#8.3) In case the expression spans over multiple lines, wrap it in parentheses for better readability.
- > Why? It shows clearly where the function starts and ends.
+ > Why? It shows clearly where the function starts and ends.
- ```js
+ ```javascript
// bad
[1, 2, 3].map(number => 'As time went by, the string containing the ' +
- `${number} became much longer. So we needed to break it over multiple ` +
- 'lines.'
+ `${number} became much longer. So we needed to break it over multiple ` +
+ 'lines.'
);
// good
[1, 2, 3].map(number => (
- `As time went by, the string containing the ${number} became much ` +
- 'longer. So we needed to break it over multiple lines.'
+ `As time went by, the string containing the ${number} became much ` +
+ 'longer. So we needed to break it over multiple lines.'
));
```
- [8.4](#8.4) If your function only takes a single argument, feel free to omit the parentheses.
- > Why? Less visual clutter.
+ > Why? Less visual clutter.
- ```js
+ ```javascript
// good
[1, 2, 3].map(x => x * x);
@@ -678,58 +764,57 @@ Other Style Guides
**[⬆ back to top](#table-of-contents)**
-
## Constructors
- [9.1](#9.1) Always use `class`. Avoid manipulating `prototype` directly.
- > Why? `class` syntax is more concise and easier to reason about.
+ > Why? `class` syntax is more concise and easier to reason about.
```javascript
// bad
function Queue(contents = []) {
- this._queue = [...contents];
+ this._queue = [...contents];
}
Queue.prototype.pop = function() {
- const value = this._queue[0];
- this._queue.splice(0, 1);
- return value;
+ const value = this._queue[0];
+ this._queue.splice(0, 1);
+ return value;
}
// good
class Queue {
- constructor(contents = []) {
- this._queue = [...contents];
- }
- pop() {
- const value = this._queue[0];
- this._queue.splice(0, 1);
- return value;
- }
+ constructor(contents = []) {
+ this._queue = [...contents];
+ }
+ pop() {
+ const value = this._queue[0];
+ this._queue.splice(0, 1);
+ return value;
+ }
}
```
- [9.2](#9.2) Use `extends` for inheritance.
- > Why? It is a built-in way to inherit prototype functionality without breaking `instanceof`.
+ > Why? It is a built-in way to inherit prototype functionality without breaking `instanceof`.
```javascript
// bad
const inherits = require('inherits');
function PeekableQueue(contents) {
- Queue.apply(this, contents);
+ Queue.apply(this, contents);
}
inherits(PeekableQueue, Queue);
PeekableQueue.prototype.peek = function() {
- return this._queue[0];
+ return this._queue[0];
}
// good
class PeekableQueue extends Queue {
- peek() {
- return this._queue[0];
- }
+ peek() {
+ return this._queue[0];
+ }
}
```
@@ -738,12 +823,12 @@ Other Style Guides
```javascript
// bad
Jedi.prototype.jump = function() {
- this.jumping = true;
- return true;
+ this.jumping = true;
+ return true;
};
Jedi.prototype.setHeight = function(height) {
- this.height = height;
+ this.height = height;
};
const luke = new Jedi();
@@ -752,21 +837,21 @@ Other Style Guides
// good
class Jedi {
- jump() {
- this.jumping = true;
- return this;
- }
+ jump() {
+ this.jumping = true;
+ return this;
+ }
- setHeight(height) {
- this.height = height;
- return this;
- }
+ setHeight(height) {
+ this.height = height;
+ return this;
+ }
}
const luke = new Jedi();
luke.jump()
- .setHeight(20);
+ .setHeight(20);
```
@@ -774,17 +859,17 @@ Other Style Guides
```javascript
class Jedi {
- constructor(options = {}) {
- this.name = options.name || 'no name';
- }
+ constructor({ name = 'no name' } = {}) {
+ this.name = name;
+ }
- getName() {
- return this.name;
- }
+ getName() {
+ return this.name;
+ }
- toString() {
- return `Jedi - ${this.getName()}`;
- }
+ toString() {
+ return `Jedi - ${this.getName()}`;
+ }
}
```
@@ -795,7 +880,7 @@ Other Style Guides
- [10.1](#10.1) Always use modules (`import`/`export`) over a non-standard module system. You can always transpile to your preferred module system.
- > Why? Modules are the future, let's start using the future now.
+ > Why? Modules are the future, let's start using the future now.
```javascript
// bad
@@ -813,7 +898,7 @@ Other Style Guides
- [10.2](#10.2) Do not use wildcard imports.
- > Why? This makes sure you have a single default export.
+ > Why? This makes sure you have a single default export.
```javascript
// bad
@@ -825,7 +910,7 @@ Other Style Guides
- [10.3](#10.3) And do not export directly from an import.
- > Why? Although the one-liner is concise, having one clear way to import and one clear way to export makes things consistent.
+ > Why? Although the one-liner is concise, having one clear way to import and one clear way to export makes things consistent.
```javascript
// bad
@@ -842,9 +927,9 @@ Other Style Guides
## Iterators and Generators
- - [11.1](#11.1) Don't use iterators. Prefer JavaScript's higher-order functions like `map()` and `reduce()` instead of loops like `for-of`.
+ - [11.1](#11.1) Prefer [JavaScript's higher-order functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) like `map()` and `reduce()` instead of loops like `for-of` unless there is a substantial performance disadvantage by doing so.
- > Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side-effects.
+ > Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side-effects.
```javascript
const numbers = [1, 2, 3, 4, 5];
@@ -852,7 +937,7 @@ Other Style Guides
// bad
let sum = 0;
for (let num of numbers) {
- sum += num;
+ sum += num;
}
sum === 15;
@@ -862,14 +947,16 @@ Other Style Guides
numbers.forEach((num) => sum += num);
sum === 15;
- // best (use the functional force)
+ // best (use the functional force, Luke)
const sum = numbers.reduce((total, num) => total + num, 0);
sum === 15;
```
- - [11.2](#11.2) Don't use generators for now.
+ - [11.2](#11.2) Only use `for-in` if you know exactly what you're doing. If unsure, prefer the options given in [11.1](#11.1).
+
+ - [11.3](#11.3) Don't use generators for now.
- > Why? They don't transpile well to ES5.
+ > Why? They don't transpile well to ES5.
**[⬆ back to top](#table-of-contents)**
@@ -880,8 +967,8 @@ Other Style Guides
```javascript
const luke = {
- jedi: true,
- age: 28,
+ jedi: true,
+ age: 28,
};
// bad
@@ -895,12 +982,12 @@ Other Style Guides
```javascript
const luke = {
- jedi: true,
- age: 28,
+ jedi: true,
+ age: 28,
};
function getProp(prop) {
- return luke[prop];
+ return luke[prop];
}
const isJedi = getProp('jedi');
@@ -911,7 +998,7 @@ Other Style Guides
## Variables
- - [13.1](#13.1) Always use `const` to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that.
+ - [13.1](#13.1) Always use `const` or `let` to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that.
```javascript
// bad
@@ -921,21 +1008,21 @@ Other Style Guides
const superPower = new SuperPower();
```
- - [13.2](#13.2) Use one `const` declaration per variable.
+ - [13.2](#13.2) Use one `const` or `let` declaration per variable.
> Why? It's easier to add new variable declarations this way, and you never have to worry about swapping out a `;` for a `,` or introducing punctuation-only diffs.
```javascript
// bad
const items = getItems(),
- goSportsTeam = true,
- dragonball = 'z';
+ goSportsTeam = true,
+ dragonball = 'z';
// bad
// (compare to above, and try to spot the mistake)
const items = getItems(),
- goSportsTeam = true;
- dragonball = 'z';
+ goSportsTeam = true;
+ dragonball = 'z';
// good
const items = getItems();
@@ -945,7 +1032,7 @@ Other Style Guides
- [13.3](#13.3) Group all your `const`s and then group all your `let`s.
- > Why? This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.
+ > Why? This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.
```javascript
// bad
@@ -970,53 +1057,93 @@ Other Style Guides
- [13.4](#13.4) Assign variables where you need them, but place them in a reasonable place.
- > Why? `let` and `const` are block scoped and not function scoped.
+ > Why? `let` and `const` are block scoped and not function scoped.
```javascript
// good
function() {
- test();
- console.log('doing stuff..');
+ test();
+ console.log('doing stuff..');
- //..other stuff..
+ //..other stuff..
- const name = getName();
+ const name = getName();
- if (name === 'test') {
- return false;
- }
+ if (name === 'test') {
+ return false;
+ }
- return name;
+ return name;
}
// bad - unnecessary function call
function(hasName) {
- const name = getName();
+ const name = getName();
- if (!hasName) {
- return false;
- }
+ if (!hasName) {
+ return false;
+ }
- this.setFirstName(name);
+ this.setFirstName(name);
- return true;
+ return true;
}
// good
function(hasName) {
- if (!hasName) {
- return false;
- }
+ if (!hasName) {
+ return false;
+ }
- const name = getName();
- this.setFirstName(name);
+ const name = getName();
+ this.setFirstName(name);
- return true;
+ return true;
}
```
-**[⬆ back to top](#table-of-contents)**
+ > Note that referencing a variable declared by `let` or `const` before they are set results in a reference error, including typeof (see [Why `typeof` is no longer "safe"](http://es-discourse.com/t/why-typeof-is-no-longer-safe/15))
+
+ ```javascript
+ if (condition) {
+ console.log(typeof value); // ReferenceError!
+ let value = "blue";
+ }
+ ```
+
+ - [13.5](#13.5) Avoid declaring unused variables, however the cases where it can be convenient (such as filtering some properties out of an object or destructuring an array, for example), prefix the variable name with `ignored`:
+
+ ```javascript
+ // bad
+ const {
+ first, // ignored
+ second, // ignored
+ third
+ } = winners;
+
+ // good
+ const {
+ first: ignoredFirst, // ignored
+ second: ignoredSecond, // ignored
+ third
+ } = winners;
+ ```
+
+ Note that our ESLint configuration is set up to error on any unused variable unless it is prefixed by `ignored`. An exception to this is argument names; any arguments listed before the first one used is OK:
+
+ ```javascript
+ // bad -- `second` is unused
+ function (first, second) {
+ return first;
+ }
+
+ // good -- `first` is listed before the used `second` argument
+ function (first, second) {
+ return second;
+ }
+ ```
+**[⬆ back to top](#table-of-contents)**
## Hoisting
@@ -1026,7 +1153,7 @@ Other Style Guides
// we know this wouldn't work (assuming there
// is no notDefined global variable)
function example() {
- console.log(notDefined); // => throws a ReferenceError
+ console.log(notDefined); // => throws a ReferenceError
}
// creating a variable declaration after you
@@ -1034,24 +1161,24 @@ Other Style Guides
// variable hoisting. Note: the assignment
// value of `true` is not hoisted.
function example() {
- console.log(declaredButNotAssigned); // => undefined
- var declaredButNotAssigned = true;
+ console.log(declaredButNotAssigned); // => undefined
+ var declaredButNotAssigned = true;
}
// The interpreter is hoisting the variable
// declaration to the top of the scope,
// which means our example could be rewritten as:
function example() {
- let declaredButNotAssigned;
- console.log(declaredButNotAssigned); // => undefined
- declaredButNotAssigned = true;
+ let declaredButNotAssigned;
+ console.log(declaredButNotAssigned); // => undefined
+ declaredButNotAssigned = true;
}
// using const and let
function example() {
- console.log(declaredButNotAssigned); // => throws a ReferenceError
- console.log(typeof declaredButNotAssigned); // => throws a ReferenceError
- const declaredButNotAssigned = true;
+ console.log(declaredButNotAssigned); // => throws a ReferenceError
+ console.log(typeof declaredButNotAssigned); // => throws a ReferenceError
+ const declaredButNotAssigned = true;
}
```
@@ -1059,13 +1186,13 @@ Other Style Guides
```javascript
function example() {
- console.log(anonymous); // => undefined
+ console.log(anonymous); // => undefined
- anonymous(); // => TypeError anonymous is not a function
+ anonymous(); // => TypeError anonymous is not a function
- var anonymous = function() {
- console.log('anonymous function expression');
- };
+ var anonymous = function() {
+ console.log('anonymous function expression');
+ };
}
```
@@ -1073,27 +1200,27 @@ Other Style Guides
```javascript
function example() {
- console.log(named); // => undefined
+ console.log(named); // => undefined
- named(); // => TypeError named is not a function
+ named(); // => TypeError named is not a function
- superPower(); // => ReferenceError superPower is not defined
+ superPower(); // => ReferenceError superPower is not defined
- var named = function superPower() {
- console.log('Flying');
- };
+ var named = function superPower() {
+ console.log('Flying');
+ };
}
// the same is true when the function name
// is the same as the variable name.
function example() {
- console.log(named); // => undefined
+ console.log(named); // => undefined
- named(); // => TypeError named is not a function
+ named(); // => TypeError named is not a function
- var named = function named() {
- console.log('named');
- }
+ var named = function named() {
+ console.log('named');
+ }
}
```
@@ -1101,14 +1228,28 @@ Other Style Guides
```javascript
function example() {
- superPower(); // => Flying
+ superPower(); // => Flying
- function superPower() {
- console.log('Flying');
- }
+ function superPower() {
+ console.log('Flying');
+ }
}
```
+ - [14.5](#14.5) ES6 `import`s are hoisted to the beginning of their module while modules imported through `require`s (ie. CommonJS modules) are not.
+
+ ```javascript
+ // This works
+ foo();
+
+ import { foo } from 'my_module';
+
+ // This will import 'imported_module' before 'required_module'
+ require('required_module');
+
+ import 'imported_module';
+ ```
+
- For more information refer to [JavaScript Scoping & Hoisting](http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting) by [Ben Cherry](http://www.adequatelygood.com/).
**[⬆ back to top](#table-of-contents)**
@@ -1116,7 +1257,7 @@ Other Style Guides
## Comparison Operators & Equality
- - [15.1](#15.1) Use `===` and `!==` over `==` and `!=`.
+ - [15.1](#15.1) Use `===` and `!==` over `==` and `!=`. Avoid `==` and `!=` because they are 'loose' equality comparisons, only evaluating equality after coercing both values following confusing and difficult to remember rules ([see MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness)).
- [15.2](#15.2) Conditional statements such as the `if` statement evaluate their expression using coercion with the `ToBoolean` abstract method and always follow these simple rules:
+ **Objects** evaluate to **true**
@@ -1127,9 +1268,9 @@ Other Style Guides
+ **Strings** evaluate to **false** if an empty string `''`, otherwise **true**
```javascript
- if ([0]) {
- // true
- // An array is an object, objects evaluate to true
+ if ([]) {
+ // true
+ // An array is an object, objects evaluate to true
}
```
@@ -1138,27 +1279,151 @@ Other Style Guides
```javascript
// bad
if (name !== '') {
- // ...stuff...
+ // ...stuff...
}
// good
if (name) {
- // ...stuff...
+ // ...stuff...
}
// bad
if (collection.length > 0) {
- // ...stuff...
+ // ...stuff...
}
// good
if (collection.length) {
- // ...stuff...
+ // ...stuff...
}
```
- [15.4](#15.4) For more information see [Truth Equality and JavaScript](http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/#more-2108) by Angus Croll.
+ - [15.5](#15.5) Use braces to create blocks in `case` and `default` clauses that contain lexical declarations (e.g. `let`, `const`, `function`, and `class`).
+
+ > Why? Lexical declarations are visible in the entire `switch` block but only get initialized when assigned, which only happens when its `case` is reached. This causes problems when multiple `case` clauses attempt to define the same thing.
+
+ ```javascript
+ // bad
+ switch (foo) {
+ case 1:
+ let x = 1;
+ break;
+ case 2:
+ const y = 2;
+ break;
+ case 3:
+ function f() {}
+ break;
+ default:
+ class C {}
+ }
+
+ // good
+ switch (foo) {
+ case 1: {
+ let x = 1;
+ break;
+ }
+ case 2: {
+ const y = 2;
+ break;
+ }
+ case 3: {
+ function f() {}
+ break;
+ }
+ case 4:
+ bar();
+ break;
+ default: {
+ class C {}
+ }
+ }
+ ```
+
+ - [15.6](#15.6) Indent one full level for case statements.
+
+ ```javascript
+ // bad
+ switch (foo) {
+ case 1:
+ break;
+ default:
+ break;
+ }
+
+ // bad
+ switch (foo) {
+ case 1:
+ break;
+ default:
+ break;
+ }
+
+ // good
+ switch (foo) {
+ case 1:
+ break;
+ default:
+ break;
+ }
+ ```
+
+ - [15.7](#15.7) Ternaries should not be nested and generally be single line expressions.
+
+ ```javascript
+ // bad
+ const foo = maybe1 > maybe2
+ ? "bar"
+ : value1 > value2 ? "baz" : null;
+
+ // better
+ const maybeNull = value1 > value2 ? 'baz'
+ : null;
+
+ const foo = maybe1 > maybe2
+ ? 'bar'
+ : maybeNull;
+
+ // best
+ const maybeNull = value1 > value2 ? 'baz' : null;
+
+ const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
+ ```
+
+ - [15.8](#15.8) Avoid unneeded ternary statements.
+
+ ```javascript
+ // bad
+ const foo = a ? a : b;
+ const bar = c ? true : false;
+ const baz = c ? false : true;
+
+ // good
+ const foo = a || b;
+ const bar = !!c;
+ const baz = !c;
+ ```
+
+ - [15.9](#15.9) Use any of the following styles for multi-line ternary statements:
+
+ ```javascript
+ // good
+ const foo = thisisasuperlongexpression ? value
+ : otherValue;
+
+ // good
+ const foo = thisisasuperlongexpression
+ ? value : otherValue;
+
+ // good
+ const foo = thisisasuperlongexpression
+ ? value
+ : otherValue;
+ ```
+
**[⬆ back to top](#table-of-contents)**
@@ -1169,14 +1434,14 @@ Other Style Guides
```javascript
// bad
if (test)
- return false;
+ return false;
// good
if (test) return false;
// good
if (test) {
- return false;
+ return false;
}
// bad
@@ -1184,29 +1449,28 @@ Other Style Guides
// good
function() {
- return false;
+ return false;
}
```
- - [16.2](#16.2) If you're using multi-line blocks with `if` and `else`, put `else` on the same line as your
- `if` block's closing brace.
+ - [16.2](#16.2) If you're using multi-line blocks with `if` and `else`, put `else` on the same line as your `if` block's closing brace.
```javascript
// bad
if (test) {
- thing1();
- thing2();
+ thing1();
+ thing2();
}
else {
- thing3();
+ thing3();
}
// good
if (test) {
- thing1();
- thing2();
+ thing1();
+ thing2();
} else {
- thing3();
+ thing3();
}
```
@@ -1216,7 +1480,7 @@ Other Style Guides
## Comments
- - [17.1](#17.1) Use `/** ... */` for multi-line comments. Include a description, specify types and values for all parameters and return values.
+ - [17.1](#17.1) Use `/** ... */` for multi-line comments. Include a description, specify types and values for all parameters and return values by using [JSDoc](http://www.2ality.com/2011/08/jsdoc-intro.html).
```javascript
// bad
@@ -1227,9 +1491,9 @@ Other Style Guides
// @return {Element} element
function make(tag) {
- // ...stuff...
+ // ...stuff...
- return element;
+ return element;
}
// good
@@ -1242,9 +1506,9 @@ Other Style Guides
*/
function make(tag) {
- // ...stuff...
+ // ...stuff...
- return element;
+ return element;
}
```
@@ -1260,49 +1524,51 @@ Other Style Guides
// bad
function getType() {
- console.log('fetching type...');
- // set the default type to 'no type'
- const type = this._type || 'no type';
+ console.log('fetching type...');
+ // set the default type to 'no type'
+ const type = this._type || 'no type';
- return type;
+ return type;
}
// good
function getType() {
- console.log('fetching type...');
+ console.log('fetching type...');
- // set the default type to 'no type'
- const type = this._type || 'no type';
+ // set the default type to 'no type'
+ const type = this._type || 'no type';
- return type;
+ return type;
}
```
- - [17.3](#17.3) Prefixing your comments with `FIXME` or `TODO` helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions are `FIXME -- need to figure this out` or `TODO -- need to implement`.
+ - [17.3](#17.3) Always put a single space between where your comment starts (ie. `/*`, `/**`, or `//`) and the comment.
+
+ - [17.4](#17.4) Prefixing your comments with `FIXME` or `TODO` helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions are `FIXME -- need to figure this out` or `TODO -- need to implement`.
- - [17.4](#17.4) Use `// FIXME:` to annotate problems.
+ - [17.5](#17.5) Use `// FIXME:` to annotate problems.
```javascript
class Calculator extends Abacus {
- constructor() {
- super();
+ constructor() {
+ super();
- // FIXME: shouldn't use a global here
- total = 0;
- }
+ // FIXME: shouldn't use a global here
+ total = 0;
+ }
}
```
- - [17.5](#17.5) Use `// TODO:` to annotate solutions to problems.
+ - [17.6](#17.6) Use `// TODO:` to annotate solutions to problems.
```javascript
class Calculator extends Abacus {
- constructor() {
- super();
+ constructor() {
+ super();
- // TODO: total should be configurable by an options param
- this.total = 0;
- }
+ // TODO: total should be configurable by an options param
+ this.total = 0;
+ }
}
```
@@ -1311,10 +1577,10 @@ Other Style Guides
## Whitespace
- - [18.1](#18.1) Use soft tabs set to 2 spaces.
+ - [18.1](#18.1) Use soft tabs set to 4 spaces.
```javascript
- // bad
+ // good
function() {
∙∙∙∙const name;
}
@@ -1324,7 +1590,7 @@ Other Style Guides
∙const name;
}
- // good
+ // bad
function() {
∙∙const name;
}
@@ -1335,48 +1601,58 @@ Other Style Guides
```javascript
// bad
function test(){
- console.log('test');
+ console.log('test');
}
// good
function test() {
- console.log('test');
+ console.log('test');
}
// bad
dog.set('attr',{
- age: '1 year',
- breed: 'Bernese Mountain Dog',
+ age: '1 year',
+ breed: 'Bernese Mountain Dog',
});
// good
dog.set('attr', {
- age: '1 year',
- breed: 'Bernese Mountain Dog',
+ age: '1 year',
+ breed: 'Bernese Mountain Dog',
});
```
- - [18.3](#18.3) Place 1 space before the opening parenthesis in control statements (`if`, `while` etc.). Place no space before the argument list in function calls and declarations.
+ - [18.3](#18.3) Place 1 space before the opening parenthesis in control statements (`if`, `while` etc.) and anonymous function declarations. Place no space before the argument list in function calls and named declarations.
```javascript
// bad
if(isJedi) {
- fight ();
+ fight ();
}
// good
if (isJedi) {
- fight();
+ fight();
+ }
+
+ // bad
+ function() {
+ console.log('Anonymous');
+ }
+
+ // good -- easier to tell this is a function decarlation rather than function call
+ function () {
+ console.log('Anonymous');
}
// bad
function fight () {
- console.log ('Swooosh!');
+ console.log ('Swooosh!');
}
// good
function fight() {
- console.log('Swooosh!');
+ console.log('Swooosh!');
}
```
@@ -1395,14 +1671,14 @@ Other Style Guides
```javascript
// bad
(function(global) {
- // ...stuff...
+ // ...stuff...
})(this);
```
```javascript
// bad
(function(global) {
- // ...stuff...
+ // ...stuff...
})(this);↵
↵
```
@@ -1410,7 +1686,7 @@ Other Style Guides
```javascript
// good
(function(global) {
- // ...stuff...
+ // ...stuff...
})(this);↵
```
@@ -1423,35 +1699,28 @@ Other Style Guides
// bad
$('#items').
- find('.selected').
- highlight().
- end().
- find('.open').
- updateCount();
+ find('.selected').
+ highlight().
+ end().
+ find('.open').
+ updateCount();
// good
$('#items')
- .find('.selected')
- .highlight()
- .end()
- .find('.open')
- .updateCount();
+ .find('.selected')
+ .highlight()
+ .end()
+ .find('.open')
+ .updateCount();
// bad
- const leds = stage.selectAll('.led').data(data).enter().append('svg:svg').class('led', true)
- .attr('width', (radius + margin) * 2).append('svg:g')
- .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
- .call(tron.led);
+ const request = fetch('/users').then(...).catch(...).finally(...);
// good
- const leds = stage.selectAll('.led')
- .data(data)
- .enter().append('svg:svg')
- .classed('led', true)
- .attr('width', (radius + margin) * 2)
- .append('svg:g')
- .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
- .call(tron.led);
+ const request = fetch('/users')
+ .then(...)
+ .catch(...)
+ .finally(...);
```
- [18.7](#18.7) Leave a blank line after blocks and before the next statement.
@@ -1459,61 +1728,209 @@ Other Style Guides
```javascript
// bad
if (foo) {
- return bar;
+ return bar;
}
return baz;
// good
if (foo) {
- return bar;
+ return bar;
}
return baz;
// bad
const obj = {
- foo() {
- },
- bar() {
- },
+ foo() {
+ },
+ bar() {
+ },
};
return obj;
// good
const obj = {
- foo() {
- },
+ foo() {
+ },
- bar() {
- },
+ bar() {
+ },
};
return obj;
// bad
const arr = [
- function foo() {
- },
- function bar() {
- },
+ function foo() {
+ },
+ function bar() {
+ },
];
return arr;
// good
const arr = [
- function foo() {
- },
+ function foo() {
+ },
- function bar() {
- },
+ function bar() {
+ },
];
return arr;
```
+ - [18.8](#18.8) Break long logical operations into multiple lines, leaving operators at the end of the line and intenting the later lines to the first line's first operand.
+
+ ```javascript
+ // bad
+ if (aReallyReallyLongExpr && anotherSuperLongExpr && wowSoManyExpr && longExprToCheckTheWorldIsOk) {
+ ...
+ }
+
+ // good
+ if (aReallyReallyLongExpr &&
+ anotherSuperLongExpr &&
+ wowSoManyExpr &&
+ longExprToCheckTheWorldIsOk) {
+ ...
+ }
+
+ // good
+ while (aReallyReallyLongExpr &&
+ anotherSuperLongExpr &&
+ wowSoManyExpr &&
+ longExprToCheckTheWorldIsOk) {
+ ...
+ }
+ ```
+
+ - [18.9](#18.9) Do not pad your blocks with blank lines.
+
+ ```javascript
+ // bad
+ function bar() {
+
+ console.log(foo);
+
+ }
+
+ // also bad
+ if (baz) {
+
+ console.log(qux);
+ } else {
+ console.log(foo);
+
+ }
+
+ // good
+ function bar() {
+ console.log(foo);
+ }
+
+ // good
+ if (baz) {
+ console.log(qux);
+ } else {
+ console.log(foo);
+ }
+ ```
+
+ - [18.10](#18.10) Do not add spaces inside parentheses.
+
+ ```javascript
+ // bad
+ function bar( foo ) {
+ return foo;
+ }
+
+ // good
+ function bar(foo) {
+ return foo;
+ }
+
+ // bad
+ if ( foo ) {
+ console.log(foo);
+ }
+
+ // good
+ if (foo) {
+ console.log(foo);
+ }
+ ```
+
+ - [18.11](#18.11) Do not add spaces inside brackets.
+
+ ```javascript
+ // bad
+ const foo = [ 1, 2, 3 ];
+ console.log(foo[ 0 ]);
+
+ // good
+ const foo = [1, 2, 3];
+ console.log(foo[0]);
+ ```
+
+ - [18.12](#18.12) Add spaces inside curly braces.
+
+ ```javascript
+ // bad
+ const foo = {clark: 'kent'};
+
+ // good
+ const foo = { clark: 'kent' };
+ ```
+
+ - [18.13](#18.13) Avoid having lines of code that are longer than 100 characters (including whitespace).
+
+ > Why? This ensures readability and maintainability.
+
+ ```javascript
+ // bad
+ const foo = 'Whatever national crop flips the window. The cartoon reverts within the screw. Whatever wizard constrains a helpful ally. The counterpart ascends!';
+
+ // bad
+ $.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' } }).done(() => console.log('Congratulations!')).fail(() => console.log('You have failed this city.'));
+
+ // good
+ const foo = 'Whatever national crop flips the window. The cartoon reverts within the screw. ' +
+ 'Whatever wizard constrains a helpful ally. The counterpart ascends!';
+
+ // good
+ $.ajax({
+ method: 'POST',
+ url: 'https://airbnb.com/',
+ data: { name: 'John' },
+ })
+ .done(() => console.log('Congratulations!'))
+ .fail(() => console.log('You have failed this city.'));
+ ```
+
+ In some cases, you can go slightly over the limit (urls, code that's *just* slightly over), but
+ our ESLint configuration is set up to warn on code lines that are over 105 characters.
+
+
+ - [18.14](#18.14) When a function call needs to be broken up into multiple lines, put arguments on a separate line, indented four spaces:
+
+ ```javascript
+ // bad
+ const foo = funcCall(this, is, a, really,
+ reallllyyyyyyy, long,
+ function, call);
+
+ // good
+ const foo = funcCall(
+ this, is, a, really,
+ reallllyyyyyyy, long,
+ function,c all
+ );
+
**[⬆ back to top](#table-of-contents)**
+
## Commas
- [19.1](#19.1) Leading commas: **Nope.**
@@ -1521,75 +1938,75 @@ Other Style Guides
```javascript
// bad
const story = [
- once
- , upon
- , aTime
+ once
+ , upon
+ , aTime
];
// good
const story = [
- once,
- upon,
- aTime,
+ once,
+ upon,
+ aTime,
];
// bad
const hero = {
- firstName: 'Ada'
- , lastName: 'Lovelace'
- , birthYear: 1815
- , superPower: 'computers'
+ firstName: 'Ada'
+ , lastName: 'Lovelace'
+ , birthYear: 1815
+ , superPower: 'computers'
};
// good
const hero = {
- firstName: 'Ada',
- lastName: 'Lovelace',
- birthYear: 1815,
- superPower: 'computers',
+ firstName: 'Ada',
+ lastName: 'Lovelace',
+ birthYear: 1815,
+ superPower: 'computers',
};
```
- [19.2](#19.2) Additional trailing comma: **Yup.**
- > Why? This leads to cleaner git diffs. Also, transpilers like Babel will remove the additional trailing comma in the transpiled code which means you don't have to worry about the [trailing comma problem](es5/README.md#commas) in legacy browsers.
+ > Why? This leads to cleaner git diffs. Also, transpilers like Babel will remove the additional trailing comma in the transpiled code which means you don't have to worry about the [trailing comma problem](es5/README.md#commas) in legacy browsers.
```javascript
// bad - git diff without trailing comma
const hero = {
- firstName: 'Florence',
- - lastName: 'Nightingale'
- + lastName: 'Nightingale',
- + inventorOf: ['coxcomb graph', 'modern nursing']
+ firstName: 'Florence',
+ - lastName: 'Nightingale'
+ + lastName: 'Nightingale',
+ + inventorOf: ['coxcomb graph', 'modern nursing']
};
// good - git diff with trailing comma
const hero = {
- firstName: 'Florence',
- lastName: 'Nightingale',
- + inventorOf: ['coxcomb chart', 'modern nursing'],
+ firstName: 'Florence',
+ lastName: 'Nightingale',
+ + inventorOf: ['coxcomb chart', 'modern nursing'],
};
// bad
const hero = {
- firstName: 'Dana',
- lastName: 'Scully'
+ firstName: 'Dana',
+ lastName: 'Scully'
};
const heroes = [
- 'Batman',
- 'Superman'
+ 'Batman',
+ 'Superman'
];
// good
const hero = {
- firstName: 'Dana',
- lastName: 'Scully',
+ firstName: 'Dana',
+ lastName: 'Scully',
};
const heroes = [
- 'Batman',
- 'Superman',
+ 'Batman',
+ 'Superman',
];
```
@@ -1598,29 +2015,20 @@ Other Style Guides
## Semicolons
- - [20.1](#20.1) **Yup.**
+ - [20.1](#20.1) **Nope.**
```javascript
// bad
(function() {
- const name = 'Skywalker'
- return name
- })()
+ const name = 'Skywalker';
+ return name;
+ })();
// good
(() => {
- const name = 'Skywalker';
- return name;
- })();
-
- // good (guards against the function becoming an argument when two files with IIFEs are concatenated)
- ;(() => {
- const name = 'Skywalker';
- return name;
- })();
- ```
-
- [Read more](http://stackoverflow.com/a/7365214/1712802).
+ const name = 'Skywalker'
+ return name
+ })()
**[⬆ back to top](#table-of-contents)**
@@ -1640,7 +2048,7 @@ Other Style Guides
const totalScore = String(this.reviewScore);
```
- - [21.3](#21.3) Numbers: Use `Number` for type casting and `parseInt` always with a radix for parsing strings.
+ - [21.3](#21.3) Numbers: Use `Number` for type casting and `parseInt` always with a radix.
```javascript
const inputValue = '4';
@@ -1709,12 +2117,12 @@ Other Style Guides
```javascript
// bad
function q() {
- // ...stuff...
+ // ...stuff...
}
// good
function query() {
- // ..stuff..
+ // ..stuff..
}
```
@@ -1736,22 +2144,22 @@ Other Style Guides
```javascript
// bad
function user(options) {
- this.name = options.name;
+ this.name = options.name;
}
const bad = new user({
- name: 'nope',
+ name: 'nope',
});
// good
- class User {
- constructor(options) {
- this.name = options.name;
- }
+ class UserPascalCase {
+ constructor(options) {
+ this.name = options.name;
+ }
}
- const good = new User({
- name: 'yup',
+ const good = new UserPascalCase({
+ name: 'yup',
});
```
@@ -1771,33 +2179,41 @@ Other Style Guides
```javascript
// bad
function foo() {
- const self = this;
- return function() {
- console.log(self);
- };
+ const self = this;
+ return function() {
+ console.log(self);
+ };
}
// bad
function foo() {
- const that = this;
- return function() {
- console.log(that);
- };
+ const that = this;
+ return function() {
+ console.log(that);
+ };
}
// good
function foo() {
- return () => {
- console.log(this);
- };
+ return () => {
+ console.log(this);
+ };
+ }
+
+ // good
+ function foo() {
+ return (function() {
+ console.log(this);
+ }).bind(this);
}
```
- - [22.6](#22.6) If your file exports a single class, your filename should be exactly the name of the class.
+ - [22.6](#22.6) If your file exports a single class, your filename should be exactly the name of the class, converted from PascalCase to snake_case.
+
```javascript
// file contents
class CheckBox {
- // ...
+ // ...
}
export default CheckBox;
@@ -1806,10 +2222,10 @@ Other Style Guides
import CheckBox from './checkBox';
// bad
- import CheckBox from './check_box';
+ import CheckBox from './CheckBox';
// good
- import CheckBox from './CheckBox';
+ import CheckBox from './check_box';
```
- [22.7](#22.7) Use camelCase when you export-default a function. Your filename should be identical to your function's name.
@@ -1825,8 +2241,8 @@ Other Style Guides
```javascript
const AirbnbStyleGuide = {
- es6: {
- }
+ es6: {
+ }
};
export default AirbnbStyleGuide;
@@ -1860,12 +2276,12 @@ Other Style Guides
```javascript
// bad
if (!dragon.age()) {
- return false;
+ return false;
}
// good
if (!dragon.hasAge()) {
- return false;
+ return false;
}
```
@@ -1873,18 +2289,18 @@ Other Style Guides
```javascript
class Jedi {
- constructor(options = {}) {
- const lightsaber = options.lightsaber || 'blue';
- this.set('lightsaber', lightsaber);
- }
+ constructor(options = {}) {
+ const lightsaber = options.lightsaber || 'blue';
+ this.set('lightsaber', lightsaber);
+ }
- set(key, val) {
- this[key] = val;
- }
+ set(key, val) {
+ this[key] = val;
+ }
- get(key) {
- return this[key];
- }
+ get(key) {
+ return this[key];
+ }
}
```
@@ -1902,7 +2318,7 @@ Other Style Guides
...
$(this).on('listingUpdated', function(e, listingId) {
- // do something with listingId
+ // do something with listingId
});
```
@@ -1915,7 +2331,7 @@ Other Style Guides
...
$(this).on('listingUpdated', function(e, data) {
- // do something with data.listingId
+ // do something with data.listingId
});
```
@@ -1942,25 +2358,25 @@ Other Style Guides
```javascript
// bad
function setSidebar() {
- $('.sidebar').hide();
+ $('.sidebar').hide();
- // ...stuff...
+ // ...stuff...
- $('.sidebar').css({
- 'background-color': 'pink'
- });
+ $('.sidebar').css({
+ 'background-color': 'pink'
+ });
}
// good
function setSidebar() {
- const $sidebar = $('.sidebar');
- $sidebar.hide();
+ const $sidebar = $('.sidebar');
+ $sidebar.hide();
- // ...stuff...
+ // ...stuff...
- $sidebar.css({
- 'background-color': 'pink'
- });
+ $sidebar.css({
+ 'background-color': 'pink'
+ });
}
```
@@ -1993,26 +2409,30 @@ Other Style Guides
**[⬆ back to top](#table-of-contents)**
+
## ECMAScript 6 Styles
- [27.1](#27.1) This is a collection of links to the various es6 features.
-1. [Arrow Functions](#arrow-functions)
-1. [Classes](#constructors)
-1. [Object Shorthand](#es6-object-shorthand)
-1. [Object Concise](#es6-object-concise)
-1. [Object Computed Properties](#es6-computed-properties)
-1. [Template Strings](#es6-template-literals)
-1. [Destructuring](#destructuring)
-1. [Default Parameters](#es6-default-parameters)
-1. [Rest](#es6-rest)
-1. [Array Spreads](#es6-array-spreads)
-1. [Let and Const](#references)
-1. [Iterators and Generators](#iterators-and-generators)
-1. [Modules](#modules)
+ 1. [Arrow Functions](#arrow-functions)
+ 1. [Classes](#constructors)
+ 1. [Object Shorthand](#es6-object-shorthand)
+ 1. [Object Concise](#es6-object-concise)
+ 1. [Object Computed Properties](#es6-computed-properties)
+ 1. [Template Strings](#es6-template-literals)
+ 1. [Destructuring](#destructuring)
+ 1. [Default Parameters](#es6-default-parameters)
+ 1. [Rest](#es6-rest)
+ 1. [Array Spreads](#es6-array-spreads)
+ 1. [Let and Const](#references)
+ 1. [Iterators and Generators](#iterators-and-generators)
+ 1. [Modules](#modules)
+
+ - [27.2](#27.2) Khan Academy has a nice section in their [Javascript styleguide](https://github.com/Khan/style-guides/blob/master/style/javascript.md) that discusses various ways to [accomplish tasks in ES6 rather than using underscore/lodash](https://github.com/Khan/style-guides/blob/master/style/javascript.md#dont-use-underscore).
**[⬆ back to top](#table-of-contents)**
+
## Testing
- [28.1](#28.1) **Yup.**
@@ -2121,6 +2541,7 @@ Other Style Guides
**[⬆ back to top](#table-of-contents)**
+
## In the Wild
This is a list of organizations that are using this style guide. Send us a pull request and we'll add you to the list.
@@ -2129,6 +2550,7 @@ Other Style Guides
- **Adult Swim**: [adult-swim/javascript](https://github.com/adult-swim/javascript)
- **Airbnb**: [airbnb/javascript](https://github.com/airbnb/javascript)
- **Apartmint**: [apartmint/javascript](https://github.com/apartmint/javascript)
+ - **Ascribe**: You're reading it!
- **Avalara**: [avalara/javascript](https://github.com/avalara/javascript)
- **Billabong**: [billabong/javascript](https://github.com/billabong/javascript)
- **Blendle**: [blendle/javascript](https://github.com/blendle/javascript)
@@ -2183,32 +2605,6 @@ Other Style Guides
**[⬆ back to top](#table-of-contents)**
-## Translation
-
- This style guide is also available in other languages:
-
- -  **Brazilian Portuguese**: [armoucar/javascript-style-guide](https://github.com/armoucar/javascript-style-guide)
- -  **Bulgarian**: [borislavvv/javascript](https://github.com/borislavvv/javascript)
- -  **Catalan**: [fpmweb/javascript-style-guide](https://github.com/fpmweb/javascript-style-guide)
- -  **Chinese (Simplified)**: [sivan/javascript-style-guide](https://github.com/sivan/javascript-style-guide)
- -  **Chinese (Traditional)**: [jigsawye/javascript](https://github.com/jigsawye/javascript)
- -  **French**: [nmussy/javascript-style-guide](https://github.com/nmussy/javascript-style-guide)
- -  **German**: [timofurrer/javascript-style-guide](https://github.com/timofurrer/javascript-style-guide)
- -  **Italian**: [sinkswim/javascript-style-guide](https://github.com/sinkswim/javascript-style-guide)
- -  **Japanese**: [mitsuruog/javacript-style-guide](https://github.com/mitsuruog/javacript-style-guide)
- -  **Korean**: [tipjs/javascript-style-guide](https://github.com/tipjs/javascript-style-guide)
- -  **Polish**: [mjurczyk/javascript](https://github.com/mjurczyk/javascript)
- -  **Russian**: [uprock/javascript](https://github.com/uprock/javascript)
- -  **Spanish**: [paolocarrasco/javascript-style-guide](https://github.com/paolocarrasco/javascript-style-guide)
- -  **Thai**: [lvarayut/javascript-style-guide](https://github.com/lvarayut/javascript-style-guide)
-
-## The JavaScript Style Guide Guide
-
- - [Reference](https://github.com/airbnb/javascript/wiki/The-JavaScript-Style-Guide-Guide)
-
-## Chat With Us About JavaScript
-
- - Find us on [gitter](https://gitter.im/airbnb/javascript).
## Contributors
@@ -2242,8 +2638,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**[⬆ back to top](#table-of-contents)**
+
## Amendments
We encourage you to fork this guide and change the rules to fit your team's style guide. Below, you may list some amendments to the style guide. This allows you to periodically update your style guide without having to deal with merge conflicts.
-
-# };
diff --git a/es5/README.md b/es5/README.md
deleted file mode 100644
index 2d24f1a4a2..0000000000
--- a/es5/README.md
+++ /dev/null
@@ -1,1742 +0,0 @@
-[](https://gitter.im/airbnb/javascript?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
-
-# Airbnb JavaScript Style Guide() {
-
-*A mostly reasonable approach to JavaScript*
-
-
-## Table of Contents
-
- 1. [Types](#types)
- 1. [Objects](#objects)
- 1. [Arrays](#arrays)
- 1. [Strings](#strings)
- 1. [Functions](#functions)
- 1. [Properties](#properties)
- 1. [Variables](#variables)
- 1. [Hoisting](#hoisting)
- 1. [Comparison Operators & Equality](#comparison-operators--equality)
- 1. [Blocks](#blocks)
- 1. [Comments](#comments)
- 1. [Whitespace](#whitespace)
- 1. [Commas](#commas)
- 1. [Semicolons](#semicolons)
- 1. [Type Casting & Coercion](#type-casting--coercion)
- 1. [Naming Conventions](#naming-conventions)
- 1. [Accessors](#accessors)
- 1. [Constructors](#constructors)
- 1. [Events](#events)
- 1. [Modules](#modules)
- 1. [jQuery](#jquery)
- 1. [ECMAScript 5 Compatibility](#ecmascript-5-compatibility)
- 1. [Testing](#testing)
- 1. [Performance](#performance)
- 1. [Resources](#resources)
- 1. [In the Wild](#in-the-wild)
- 1. [Translation](#translation)
- 1. [The JavaScript Style Guide Guide](#the-javascript-style-guide-guide)
- 1. [Chat With Us About Javascript](#chat-with-us-about-javascript)
- 1. [Contributors](#contributors)
- 1. [License](#license)
-
-## Types
-
- - **Primitives**: When you access a primitive type you work directly on its value.
-
- + `string`
- + `number`
- + `boolean`
- + `null`
- + `undefined`
-
- ```javascript
- var foo = 1;
- var bar = foo;
-
- bar = 9;
-
- console.log(foo, bar); // => 1, 9
- ```
- - **Complex**: When you access a complex type you work on a reference to its value.
-
- + `object`
- + `array`
- + `function`
-
- ```javascript
- var foo = [1, 2];
- var bar = foo;
-
- bar[0] = 9;
-
- console.log(foo[0], bar[0]); // => 9, 9
- ```
-
-**[⬆ back to top](#table-of-contents)**
-
-## Objects
-
- - Use the literal syntax for object creation.
-
- ```javascript
- // bad
- var item = new Object();
-
- // good
- var item = {};
- ```
-
- - Don't use [reserved words](http://es5.github.io/#x7.6.1) as keys. It won't work in IE8. [More info](https://github.com/airbnb/javascript/issues/61).
-
- ```javascript
- // bad
- var superman = {
- default: { clark: 'kent' },
- private: true
- };
-
- // good
- var superman = {
- defaults: { clark: 'kent' },
- hidden: true
- };
- ```
-
- - Use readable synonyms in place of reserved words.
-
- ```javascript
- // bad
- var superman = {
- class: 'alien'
- };
-
- // bad
- var superman = {
- klass: 'alien'
- };
-
- // good
- var superman = {
- type: 'alien'
- };
- ```
-
-**[⬆ back to top](#table-of-contents)**
-
-## Arrays
-
- - Use the literal syntax for array creation.
-
- ```javascript
- // bad
- var items = new Array();
-
- // good
- var items = [];
- ```
-
- - Use Array#push instead of direct assignment to add items to an array.
-
- ```javascript
- var someStack = [];
-
-
- // bad
- someStack[someStack.length] = 'abracadabra';
-
- // good
- someStack.push('abracadabra');
- ```
-
- - When you need to copy an array use Array#slice. [jsPerf](http://jsperf.com/converting-arguments-to-an-array/7)
-
- ```javascript
- var len = items.length;
- var itemsCopy = [];
- var i;
-
- // bad
- for (i = 0; i < len; i++) {
- itemsCopy[i] = items[i];
- }
-
- // good
- itemsCopy = items.slice();
- ```
-
- - To convert an array-like object to an array, use Array#slice.
-
- ```javascript
- function trigger() {
- var args = Array.prototype.slice.call(arguments);
- ...
- }
- ```
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## Strings
-
- - Use single quotes `''` for strings.
-
- ```javascript
- // bad
- var name = "Bob Parr";
-
- // good
- var name = 'Bob Parr';
-
- // bad
- var fullName = "Bob " + this.lastName;
-
- // good
- var fullName = 'Bob ' + this.lastName;
- ```
-
- - Strings longer than 100 characters should be written across multiple lines using string concatenation.
- - Note: If overused, long strings with concatenation could impact performance. [jsPerf](http://jsperf.com/ya-string-concat) & [Discussion](https://github.com/airbnb/javascript/issues/40).
-
- ```javascript
- // bad
- var errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';
-
- // bad
- var errorMessage = 'This is a super long error that was thrown because \
- of Batman. When you stop to think about how Batman had anything to do \
- with this, you would get nowhere \
- fast.';
-
- // good
- var errorMessage = 'This is a super long error that was thrown because ' +
- 'of Batman. When you stop to think about how Batman had anything to do ' +
- 'with this, you would get nowhere fast.';
- ```
-
- - When programmatically building up a string, use Array#join instead of string concatenation. Mostly for IE: [jsPerf](http://jsperf.com/string-vs-array-concat/2).
-
- ```javascript
- var items;
- var messages;
- var length;
- var i;
-
- messages = [{
- state: 'success',
- message: 'This one worked.'
- }, {
- state: 'success',
- message: 'This one worked as well.'
- }, {
- state: 'error',
- message: 'This one did not work.'
- }];
-
- length = messages.length;
-
- // bad
- function inbox(messages) {
- items = '
';
-
- for (i = 0; i < length; i++) {
- items += '- ' + messages[i].message + '
';
- }
-
- return items + '
';
- }
-
- // good
- function inbox(messages) {
- items = [];
-
- for (i = 0; i < length; i++) {
- // use direct assignment in this case because we're micro-optimizing.
- items[i] = '' + messages[i].message + '';
- }
-
- return '';
- }
- ```
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## Functions
-
- - Function expressions:
-
- ```javascript
- // anonymous function expression
- var anonymous = function() {
- return true;
- };
-
- // named function expression
- var named = function named() {
- return true;
- };
-
- // immediately-invoked function expression (IIFE)
- (function() {
- console.log('Welcome to the Internet. Please follow me.');
- })();
- ```
-
- - Never declare a function in a non-function block (if, while, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears.
- - **Note:** ECMA-262 defines a `block` as a list of statements. A function declaration is not a statement. [Read ECMA-262's note on this issue](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf#page=97).
-
- ```javascript
- // bad
- if (currentUser) {
- function test() {
- console.log('Nope.');
- }
- }
-
- // good
- var test;
- if (currentUser) {
- test = function test() {
- console.log('Yup.');
- };
- }
- ```
-
- - Never name a parameter `arguments`. This will take precedence over the `arguments` object that is given to every function scope.
-
- ```javascript
- // bad
- function nope(name, options, arguments) {
- // ...stuff...
- }
-
- // good
- function yup(name, options, args) {
- // ...stuff...
- }
- ```
-
-**[⬆ back to top](#table-of-contents)**
-
-
-
-## Properties
-
- - Use dot notation when accessing properties.
-
- ```javascript
- var luke = {
- jedi: true,
- age: 28
- };
-
- // bad
- var isJedi = luke['jedi'];
-
- // good
- var isJedi = luke.jedi;
- ```
-
- - Use subscript notation `[]` when accessing properties with a variable.
-
- ```javascript
- var luke = {
- jedi: true,
- age: 28
- };
-
- function getProp(prop) {
- return luke[prop];
- }
-
- var isJedi = getProp('jedi');
- ```
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## Variables
-
- - Always use `var` to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that.
-
- ```javascript
- // bad
- superPower = new SuperPower();
-
- // good
- var superPower = new SuperPower();
- ```
-
- - Use one `var` declaration per variable.
- It's easier to add new variable declarations this way, and you never have
- to worry about swapping out a `;` for a `,` or introducing punctuation-only
- diffs.
-
- ```javascript
- // bad
- var items = getItems(),
- goSportsTeam = true,
- dragonball = 'z';
-
- // bad
- // (compare to above, and try to spot the mistake)
- var items = getItems(),
- goSportsTeam = true;
- dragonball = 'z';
-
- // good
- var items = getItems();
- var goSportsTeam = true;
- var dragonball = 'z';
- ```
-
- - Declare unassigned variables last. This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.
-
- ```javascript
- // bad
- var i, len, dragonball,
- items = getItems(),
- goSportsTeam = true;
-
- // bad
- var i;
- var items = getItems();
- var dragonball;
- var goSportsTeam = true;
- var len;
-
- // good
- var items = getItems();
- var goSportsTeam = true;
- var dragonball;
- var length;
- var i;
- ```
-
- - Assign variables at the top of their scope. This helps avoid issues with variable declaration and assignment hoisting related issues.
-
- ```javascript
- // bad
- function() {
- test();
- console.log('doing stuff..');
-
- //..other stuff..
-
- var name = getName();
-
- if (name === 'test') {
- return false;
- }
-
- return name;
- }
-
- // good
- function() {
- var name = getName();
-
- test();
- console.log('doing stuff..');
-
- //..other stuff..
-
- if (name === 'test') {
- return false;
- }
-
- return name;
- }
-
- // bad - unnecessary function call
- function() {
- var name = getName();
-
- if (!arguments.length) {
- return false;
- }
-
- this.setFirstName(name);
-
- return true;
- }
-
- // good
- function() {
- var name;
-
- if (!arguments.length) {
- return false;
- }
-
- name = getName();
- this.setFirstName(name);
-
- return true;
- }
- ```
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## Hoisting
-
- - Variable declarations get hoisted to the top of their scope, but their assignment does not.
-
- ```javascript
- // we know this wouldn't work (assuming there
- // is no notDefined global variable)
- function example() {
- console.log(notDefined); // => throws a ReferenceError
- }
-
- // creating a variable declaration after you
- // reference the variable will work due to
- // variable hoisting. Note: the assignment
- // value of `true` is not hoisted.
- function example() {
- console.log(declaredButNotAssigned); // => undefined
- var declaredButNotAssigned = true;
- }
-
- // The interpreter is hoisting the variable
- // declaration to the top of the scope,
- // which means our example could be rewritten as:
- function example() {
- var declaredButNotAssigned;
- console.log(declaredButNotAssigned); // => undefined
- declaredButNotAssigned = true;
- }
- ```
-
- - Anonymous function expressions hoist their variable name, but not the function assignment.
-
- ```javascript
- function example() {
- console.log(anonymous); // => undefined
-
- anonymous(); // => TypeError anonymous is not a function
-
- var anonymous = function() {
- console.log('anonymous function expression');
- };
- }
- ```
-
- - Named function expressions hoist the variable name, not the function name or the function body.
-
- ```javascript
- function example() {
- console.log(named); // => undefined
-
- named(); // => TypeError named is not a function
-
- superPower(); // => ReferenceError superPower is not defined
-
- var named = function superPower() {
- console.log('Flying');
- };
- }
-
- // the same is true when the function name
- // is the same as the variable name.
- function example() {
- console.log(named); // => undefined
-
- named(); // => TypeError named is not a function
-
- var named = function named() {
- console.log('named');
- }
- }
- ```
-
- - Function declarations hoist their name and the function body.
-
- ```javascript
- function example() {
- superPower(); // => Flying
-
- function superPower() {
- console.log('Flying');
- }
- }
- ```
-
- - For more information refer to [JavaScript Scoping & Hoisting](http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting) by [Ben Cherry](http://www.adequatelygood.com/).
-
-**[⬆ back to top](#table-of-contents)**
-
-
-
-## Comparison Operators & Equality
-
- - Use `===` and `!==` over `==` and `!=`.
- - Conditional statements such as the `if` statement evaluate their expression using coercion with the `ToBoolean` abstract method and always follow these simple rules:
-
- + **Objects** evaluate to **true**
- + **Undefined** evaluates to **false**
- + **Null** evaluates to **false**
- + **Booleans** evaluate to **the value of the boolean**
- + **Numbers** evaluate to **false** if **+0, -0, or NaN**, otherwise **true**
- + **Strings** evaluate to **false** if an empty string `''`, otherwise **true**
-
- ```javascript
- if ([0]) {
- // true
- // An array is an object, objects evaluate to true
- }
- ```
-
- - Use shortcuts.
-
- ```javascript
- // bad
- if (name !== '') {
- // ...stuff...
- }
-
- // good
- if (name) {
- // ...stuff...
- }
-
- // bad
- if (collection.length > 0) {
- // ...stuff...
- }
-
- // good
- if (collection.length) {
- // ...stuff...
- }
- ```
-
- - For more information see [Truth Equality and JavaScript](http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/#more-2108) by Angus Croll.
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## Blocks
-
- - Use braces with all multi-line blocks.
-
- ```javascript
- // bad
- if (test)
- return false;
-
- // good
- if (test) return false;
-
- // good
- if (test) {
- return false;
- }
-
- // bad
- function() { return false; }
-
- // good
- function() {
- return false;
- }
- ```
-
- - If you're using multi-line blocks with `if` and `else`, put `else` on the same line as your
- `if` block's closing brace.
-
- ```javascript
- // bad
- if (test) {
- thing1();
- thing2();
- }
- else {
- thing3();
- }
-
- // good
- if (test) {
- thing1();
- thing2();
- } else {
- thing3();
- }
- ```
-
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## Comments
-
- - Use `/** ... */` for multi-line comments. Include a description, specify types and values for all parameters and return values.
-
- ```javascript
- // bad
- // make() returns a new element
- // based on the passed in tag name
- //
- // @param {String} tag
- // @return {Element} element
- function make(tag) {
-
- // ...stuff...
-
- return element;
- }
-
- // good
- /**
- * make() returns a new element
- * based on the passed in tag name
- *
- * @param {String} tag
- * @return {Element} element
- */
- function make(tag) {
-
- // ...stuff...
-
- return element;
- }
- ```
-
- - Use `//` for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment.
-
- ```javascript
- // bad
- var active = true; // is current tab
-
- // good
- // is current tab
- var active = true;
-
- // bad
- function getType() {
- console.log('fetching type...');
- // set the default type to 'no type'
- var type = this._type || 'no type';
-
- return type;
- }
-
- // good
- function getType() {
- console.log('fetching type...');
-
- // set the default type to 'no type'
- var type = this._type || 'no type';
-
- return type;
- }
- ```
-
- - Prefixing your comments with `FIXME` or `TODO` helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions are `FIXME -- need to figure this out` or `TODO -- need to implement`.
-
- - Use `// FIXME:` to annotate problems.
-
- ```javascript
- function Calculator() {
-
- // FIXME: shouldn't use a global here
- total = 0;
-
- return this;
- }
- ```
-
- - Use `// TODO:` to annotate solutions to problems.
-
- ```javascript
- function Calculator() {
-
- // TODO: total should be configurable by an options param
- this.total = 0;
-
- return this;
- }
- ```
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## Whitespace
-
- - Use soft tabs set to 2 spaces.
-
- ```javascript
- // bad
- function() {
- ∙∙∙∙var name;
- }
-
- // bad
- function() {
- ∙var name;
- }
-
- // good
- function() {
- ∙∙var name;
- }
- ```
-
- - Place 1 space before the leading brace.
-
- ```javascript
- // bad
- function test(){
- console.log('test');
- }
-
- // good
- function test() {
- console.log('test');
- }
-
- // bad
- dog.set('attr',{
- age: '1 year',
- breed: 'Bernese Mountain Dog'
- });
-
- // good
- dog.set('attr', {
- age: '1 year',
- breed: 'Bernese Mountain Dog'
- });
- ```
-
- - Place 1 space before the opening parenthesis in control statements (`if`, `while` etc.). Place no space before the argument list in function calls and declarations.
-
- ```javascript
- // bad
- if(isJedi) {
- fight ();
- }
-
- // good
- if (isJedi) {
- fight();
- }
-
- // bad
- function fight () {
- console.log ('Swooosh!');
- }
-
- // good
- function fight() {
- console.log('Swooosh!');
- }
- ```
-
- - Set off operators with spaces.
-
- ```javascript
- // bad
- var x=y+5;
-
- // good
- var x = y + 5;
- ```
-
- - End files with a single newline character.
-
- ```javascript
- // bad
- (function(global) {
- // ...stuff...
- })(this);
- ```
-
- ```javascript
- // bad
- (function(global) {
- // ...stuff...
- })(this);↵
- ↵
- ```
-
- ```javascript
- // good
- (function(global) {
- // ...stuff...
- })(this);↵
- ```
-
- - Use indentation when making long method chains. Use a leading dot, which
- emphasizes that the line is a method call, not a new statement.
-
- ```javascript
- // bad
- $('#items').find('.selected').highlight().end().find('.open').updateCount();
-
- // bad
- $('#items').
- find('.selected').
- highlight().
- end().
- find('.open').
- updateCount();
-
- // good
- $('#items')
- .find('.selected')
- .highlight()
- .end()
- .find('.open')
- .updateCount();
-
- // bad
- var leds = stage.selectAll('.led').data(data).enter().append('svg:svg').classed('led', true)
- .attr('width', (radius + margin) * 2).append('svg:g')
- .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
- .call(tron.led);
-
- // good
- var leds = stage.selectAll('.led')
- .data(data)
- .enter().append('svg:svg')
- .classed('led', true)
- .attr('width', (radius + margin) * 2)
- .append('svg:g')
- .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
- .call(tron.led);
- ```
-
- - Leave a blank line after blocks and before the next statement
-
- ```javascript
- // bad
- if (foo) {
- return bar;
- }
- return baz;
-
- // good
- if (foo) {
- return bar;
- }
-
- return baz;
-
- // bad
- var obj = {
- foo: function() {
- },
- bar: function() {
- }
- };
- return obj;
-
- // good
- var obj = {
- foo: function() {
- },
-
- bar: function() {
- }
- };
-
- return obj;
- ```
-
-
-**[⬆ back to top](#table-of-contents)**
-
-## Commas
-
- - Leading commas: **Nope.**
-
- ```javascript
- // bad
- var story = [
- once
- , upon
- , aTime
- ];
-
- // good
- var story = [
- once,
- upon,
- aTime
- ];
-
- // bad
- var hero = {
- firstName: 'Bob'
- , lastName: 'Parr'
- , heroName: 'Mr. Incredible'
- , superPower: 'strength'
- };
-
- // good
- var hero = {
- firstName: 'Bob',
- lastName: 'Parr',
- heroName: 'Mr. Incredible',
- superPower: 'strength'
- };
- ```
-
- - Additional trailing comma: **Nope.** This can cause problems with IE6/7 and IE9 if it's in quirksmode. Also, in some implementations of ES3 would add length to an array if it had an additional trailing comma. This was clarified in ES5 ([source](http://es5.github.io/#D)):
-
- > Edition 5 clarifies the fact that a trailing comma at the end of an ArrayInitialiser does not add to the length of the array. This is not a semantic change from Edition 3 but some implementations may have previously misinterpreted this.
-
- ```javascript
- // bad
- var hero = {
- firstName: 'Kevin',
- lastName: 'Flynn',
- };
-
- var heroes = [
- 'Batman',
- 'Superman',
- ];
-
- // good
- var hero = {
- firstName: 'Kevin',
- lastName: 'Flynn'
- };
-
- var heroes = [
- 'Batman',
- 'Superman'
- ];
- ```
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## Semicolons
-
- - **Yup.**
-
- ```javascript
- // bad
- (function() {
- var name = 'Skywalker'
- return name
- })()
-
- // good
- (function() {
- var name = 'Skywalker';
- return name;
- })();
-
- // good (guards against the function becoming an argument when two files with IIFEs are concatenated)
- ;(function() {
- var name = 'Skywalker';
- return name;
- })();
- ```
-
- [Read more](http://stackoverflow.com/a/7365214/1712802).
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## Type Casting & Coercion
-
- - Perform type coercion at the beginning of the statement.
- - Strings:
-
- ```javascript
- // => this.reviewScore = 9;
-
- // bad
- var totalScore = this.reviewScore + '';
-
- // good
- var totalScore = '' + this.reviewScore;
-
- // bad
- var totalScore = '' + this.reviewScore + ' total score';
-
- // good
- var totalScore = this.reviewScore + ' total score';
- ```
-
- - Use `parseInt` for Numbers and always with a radix for type casting.
-
- ```javascript
- var inputValue = '4';
-
- // bad
- var val = new Number(inputValue);
-
- // bad
- var val = +inputValue;
-
- // bad
- var val = inputValue >> 0;
-
- // bad
- var val = parseInt(inputValue);
-
- // good
- var val = Number(inputValue);
-
- // good
- var val = parseInt(inputValue, 10);
- ```
-
- - If for whatever reason you are doing something wild and `parseInt` is your bottleneck and need to use Bitshift for [performance reasons](http://jsperf.com/coercion-vs-casting/3), leave a comment explaining why and what you're doing.
-
- ```javascript
- // good
- /**
- * parseInt was the reason my code was slow.
- * Bitshifting the String to coerce it to a
- * Number made it a lot faster.
- */
- var val = inputValue >> 0;
- ```
-
- - **Note:** Be careful when using bitshift operations. Numbers are represented as [64-bit values](http://es5.github.io/#x4.3.19), but Bitshift operations always return a 32-bit integer ([source](http://es5.github.io/#x11.7)). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. [Discussion](https://github.com/airbnb/javascript/issues/109). Largest signed 32-bit Int is 2,147,483,647:
-
- ```javascript
- 2147483647 >> 0 //=> 2147483647
- 2147483648 >> 0 //=> -2147483648
- 2147483649 >> 0 //=> -2147483647
- ```
-
- - Booleans:
-
- ```javascript
- var age = 0;
-
- // bad
- var hasAge = new Boolean(age);
-
- // good
- var hasAge = Boolean(age);
-
- // good
- var hasAge = !!age;
- ```
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## Naming Conventions
-
- - Avoid single letter names. Be descriptive with your naming.
-
- ```javascript
- // bad
- function q() {
- // ...stuff...
- }
-
- // good
- function query() {
- // ..stuff..
- }
- ```
-
- - Use camelCase when naming objects, functions, and instances.
-
- ```javascript
- // bad
- var OBJEcttsssss = {};
- var this_is_my_object = {};
- var o = {};
- function c() {}
-
- // good
- var thisIsMyObject = {};
- function thisIsMyFunction() {}
- ```
-
- - Use PascalCase when naming constructors or classes.
-
- ```javascript
- // bad
- function user(options) {
- this.name = options.name;
- }
-
- var bad = new user({
- name: 'nope'
- });
-
- // good
- function User(options) {
- this.name = options.name;
- }
-
- var good = new User({
- name: 'yup'
- });
- ```
-
- - Use a leading underscore `_` when naming private properties.
-
- ```javascript
- // bad
- this.__firstName__ = 'Panda';
- this.firstName_ = 'Panda';
-
- // good
- this._firstName = 'Panda';
- ```
-
- - When saving a reference to `this` use `_this`.
-
- ```javascript
- // bad
- function() {
- var self = this;
- return function() {
- console.log(self);
- };
- }
-
- // bad
- function() {
- var that = this;
- return function() {
- console.log(that);
- };
- }
-
- // good
- function() {
- var _this = this;
- return function() {
- console.log(_this);
- };
- }
- ```
-
- - Name your functions. This is helpful for stack traces.
-
- ```javascript
- // bad
- var log = function(msg) {
- console.log(msg);
- };
-
- // good
- var log = function log(msg) {
- console.log(msg);
- };
- ```
-
- - **Note:** IE8 and below exhibit some quirks with named function expressions. See [http://kangax.github.io/nfe/](http://kangax.github.io/nfe/) for more info.
-
- - If your file exports a single class, your filename should be exactly the name of the class.
- ```javascript
- // file contents
- class CheckBox {
- // ...
- }
- module.exports = CheckBox;
-
- // in some other file
- // bad
- var CheckBox = require('./checkBox');
-
- // bad
- var CheckBox = require('./check_box');
-
- // good
- var CheckBox = require('./CheckBox');
- ```
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## Accessors
-
- - Accessor functions for properties are not required.
- - If you do make accessor functions use getVal() and setVal('hello').
-
- ```javascript
- // bad
- dragon.age();
-
- // good
- dragon.getAge();
-
- // bad
- dragon.age(25);
-
- // good
- dragon.setAge(25);
- ```
-
- - If the property is a boolean, use isVal() or hasVal().
-
- ```javascript
- // bad
- if (!dragon.age()) {
- return false;
- }
-
- // good
- if (!dragon.hasAge()) {
- return false;
- }
- ```
-
- - It's okay to create get() and set() functions, but be consistent.
-
- ```javascript
- function Jedi(options) {
- options || (options = {});
- var lightsaber = options.lightsaber || 'blue';
- this.set('lightsaber', lightsaber);
- }
-
- Jedi.prototype.set = function(key, val) {
- this[key] = val;
- };
-
- Jedi.prototype.get = function(key) {
- return this[key];
- };
- ```
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## Constructors
-
- - Assign methods to the prototype object, instead of overwriting the prototype with a new object. Overwriting the prototype makes inheritance impossible: by resetting the prototype you'll overwrite the base!
-
- ```javascript
- function Jedi() {
- console.log('new jedi');
- }
-
- // bad
- Jedi.prototype = {
- fight: function fight() {
- console.log('fighting');
- },
-
- block: function block() {
- console.log('blocking');
- }
- };
-
- // good
- Jedi.prototype.fight = function fight() {
- console.log('fighting');
- };
-
- Jedi.prototype.block = function block() {
- console.log('blocking');
- };
- ```
-
- - Methods can return `this` to help with method chaining.
-
- ```javascript
- // bad
- Jedi.prototype.jump = function() {
- this.jumping = true;
- return true;
- };
-
- Jedi.prototype.setHeight = function(height) {
- this.height = height;
- };
-
- var luke = new Jedi();
- luke.jump(); // => true
- luke.setHeight(20); // => undefined
-
- // good
- Jedi.prototype.jump = function() {
- this.jumping = true;
- return this;
- };
-
- Jedi.prototype.setHeight = function(height) {
- this.height = height;
- return this;
- };
-
- var luke = new Jedi();
-
- luke.jump()
- .setHeight(20);
- ```
-
-
- - It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.
-
- ```javascript
- function Jedi(options) {
- options || (options = {});
- this.name = options.name || 'no name';
- }
-
- Jedi.prototype.getName = function getName() {
- return this.name;
- };
-
- Jedi.prototype.toString = function toString() {
- return 'Jedi - ' + this.getName();
- };
- ```
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## Events
-
- - When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass a hash instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of:
-
- ```js
- // bad
- $(this).trigger('listingUpdated', listing.id);
-
- ...
-
- $(this).on('listingUpdated', function(e, listingId) {
- // do something with listingId
- });
- ```
-
- prefer:
-
- ```js
- // good
- $(this).trigger('listingUpdated', { listingId : listing.id });
-
- ...
-
- $(this).on('listingUpdated', function(e, data) {
- // do something with data.listingId
- });
- ```
-
- **[⬆ back to top](#table-of-contents)**
-
-
-## Modules
-
- - The module should start with a `!`. This ensures that if a malformed module forgets to include a final semicolon there aren't errors in production when the scripts get concatenated. [Explanation](https://github.com/airbnb/javascript/issues/44#issuecomment-13063933)
- - The file should be named with camelCase, live in a folder with the same name, and match the name of the single export.
- - Add a method called `noConflict()` that sets the exported module to the previous version and returns this one.
- - Always declare `'use strict';` at the top of the module.
-
- ```javascript
- // fancyInput/fancyInput.js
-
- !function(global) {
- 'use strict';
-
- var previousFancyInput = global.FancyInput;
-
- function FancyInput(options) {
- this.options = options || {};
- }
-
- FancyInput.noConflict = function noConflict() {
- global.FancyInput = previousFancyInput;
- return FancyInput;
- };
-
- global.FancyInput = FancyInput;
- }(this);
- ```
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## jQuery
-
- - Prefix jQuery object variables with a `$`.
-
- ```javascript
- // bad
- var sidebar = $('.sidebar');
-
- // good
- var $sidebar = $('.sidebar');
- ```
-
- - Cache jQuery lookups.
-
- ```javascript
- // bad
- function setSidebar() {
- $('.sidebar').hide();
-
- // ...stuff...
-
- $('.sidebar').css({
- 'background-color': 'pink'
- });
- }
-
- // good
- function setSidebar() {
- var $sidebar = $('.sidebar');
- $sidebar.hide();
-
- // ...stuff...
-
- $sidebar.css({
- 'background-color': 'pink'
- });
- }
- ```
-
- - For DOM queries use Cascading `$('.sidebar ul')` or parent > child `$('.sidebar > ul')`. [jsPerf](http://jsperf.com/jquery-find-vs-context-sel/16)
- - Use `find` with scoped jQuery object queries.
-
- ```javascript
- // bad
- $('ul', '.sidebar').hide();
-
- // bad
- $('.sidebar').find('ul').hide();
-
- // good
- $('.sidebar ul').hide();
-
- // good
- $('.sidebar > ul').hide();
-
- // good
- $sidebar.find('ul').hide();
- ```
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## ECMAScript 5 Compatibility
-
- - Refer to [Kangax](https://twitter.com/kangax/)'s ES5 [compatibility table](http://kangax.github.com/es5-compat-table/).
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## Testing
-
- - **Yup.**
-
- ```javascript
- function() {
- return true;
- }
- ```
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## Performance
-
- - [On Layout & Web Performance](http://kellegous.com/j/2013/01/26/layout-performance/)
- - [String vs Array Concat](http://jsperf.com/string-vs-array-concat/2)
- - [Try/Catch Cost In a Loop](http://jsperf.com/try-catch-in-loop-cost)
- - [Bang Function](http://jsperf.com/bang-function)
- - [jQuery Find vs Context, Selector](http://jsperf.com/jquery-find-vs-context-sel/13)
- - [innerHTML vs textContent for script text](http://jsperf.com/innerhtml-vs-textcontent-for-script-text)
- - [Long String Concatenation](http://jsperf.com/ya-string-concat)
- - Loading...
-
-**[⬆ back to top](#table-of-contents)**
-
-
-## Resources
-
-
-**Read This**
-
- - [Annotated ECMAScript 5.1](http://es5.github.com/)
-
-**Tools**
-
- - Code Style Linters
- + [JSHint](http://www.jshint.com/) - [Airbnb Style .jshintrc](https://github.com/airbnb/javascript/blob/master/linters/jshintrc)
- + [JSCS](https://github.com/jscs-dev/node-jscs) - [Airbnb Style Preset](https://github.com/jscs-dev/node-jscs/blob/master/presets/airbnb.json)
-
-**Other Style Guides**
-
- - [Google JavaScript Style Guide](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml)
- - [jQuery Core Style Guidelines](http://docs.jquery.com/JQuery_Core_Style_Guidelines)
- - [Principles of Writing Consistent, Idiomatic JavaScript](https://github.com/rwldrn/idiomatic.js/)
- - [JavaScript Standard Style](https://github.com/feross/standard)
-
-**Other Styles**
-
- - [Naming this in nested functions](https://gist.github.com/4135065) - Christian Johansen
- - [Conditional Callbacks](https://github.com/airbnb/javascript/issues/52) - Ross Allen
- - [Popular JavaScript Coding Conventions on Github](http://sideeffect.kr/popularconvention/#javascript) - JeongHoon Byun
- - [Multiple var statements in JavaScript, not superfluous](http://benalman.com/news/2012/05/multiple-var-statements-javascript/) - Ben Alman
-
-**Further Reading**
-
- - [Understanding JavaScript Closures](http://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/) - Angus Croll
- - [Basic JavaScript for the impatient programmer](http://www.2ality.com/2013/06/basic-javascript.html) - Dr. Axel Rauschmayer
- - [You Might Not Need jQuery](http://youmightnotneedjquery.com/) - Zack Bloom & Adam Schwartz
- - [ES6 Features](https://github.com/lukehoban/es6features) - Luke Hoban
- - [Frontend Guidelines](https://github.com/bendc/frontend-guidelines) - Benjamin De Cock
-
-**Books**
-
- - [JavaScript: The Good Parts](http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742) - Douglas Crockford
- - [JavaScript Patterns](http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752) - Stoyan Stefanov
- - [Pro JavaScript Design Patterns](http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X) - Ross Harmes and Dustin Diaz
- - [High Performance Web Sites: Essential Knowledge for Front-End Engineers](http://www.amazon.com/High-Performance-Web-Sites-Essential/dp/0596529309) - Steve Souders
- - [Maintainable JavaScript](http://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zakas/dp/1449327680) - Nicholas C. Zakas
- - [JavaScript Web Applications](http://www.amazon.com/JavaScript-Web-Applications-Alex-MacCaw/dp/144930351X) - Alex MacCaw
- - [Pro JavaScript Techniques](http://www.amazon.com/Pro-JavaScript-Techniques-John-Resig/dp/1590597273) - John Resig
- - [Smashing Node.js: JavaScript Everywhere](http://www.amazon.com/Smashing-Node-js-JavaScript-Everywhere-Magazine/dp/1119962595) - Guillermo Rauch
- - [Secrets of the JavaScript Ninja](http://www.amazon.com/Secrets-JavaScript-Ninja-John-Resig/dp/193398869X) - John Resig and Bear Bibeault
- - [Human JavaScript](http://humanjavascript.com/) - Henrik Joreteg
- - [Superhero.js](http://superherojs.com/) - Kim Joar Bekkelund, Mads Mobæk, & Olav Bjorkoy
- - [JSBooks](http://jsbooks.revolunet.com/) - Julien Bouquillon
- - [Third Party JavaScript](http://manning.com/vinegar/) - Ben Vinegar and Anton Kovalyov
- - [Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript](http://amzn.com/0321812182) - David Herman
- - [Eloquent JavaScript](http://eloquentjavascript.net) - Marijn Haverbeke
- - [You Don't Know JS](https://github.com/getify/You-Dont-Know-JS) - Kyle Simpson
-
-**Blogs**
-
- - [DailyJS](http://dailyjs.com/)
- - [JavaScript Weekly](http://javascriptweekly.com/)
- - [JavaScript, JavaScript...](http://javascriptweblog.wordpress.com/)
- - [Bocoup Weblog](http://weblog.bocoup.com/)
- - [Adequately Good](http://www.adequatelygood.com/)
- - [NCZOnline](http://www.nczonline.net/)
- - [Perfection Kills](http://perfectionkills.com/)
- - [Ben Alman](http://benalman.com/)
- - [Dmitry Baranovskiy](http://dmitry.baranovskiy.com/)
- - [Dustin Diaz](http://dustindiaz.com/)
- - [nettuts](http://net.tutsplus.com/?s=javascript)
-
-**Podcasts**
-
- - [JavaScript Jabber](http://devchat.tv/js-jabber/)
-
-
-**[⬆ back to top](#table-of-contents)**
-
-## In the Wild
-
- This is a list of organizations that are using this style guide. Send us a pull request or open an issue and we'll add you to the list.
-
- - **Aan Zee**: [AanZee/javascript](https://github.com/AanZee/javascript)
- - **Adult Swim**: [adult-swim/javascript](https://github.com/adult-swim/javascript)
- - **Airbnb**: [airbnb/javascript](https://github.com/airbnb/javascript)
- - **Apartmint**: [apartmint/javascript](https://github.com/apartmint/javascript)
- - **Avalara**: [avalara/javascript](https://github.com/avalara/javascript)
- - **Billabong**: [billabong/javascript](https://github.com/billabong/javascript)
- - **Compass Learning**: [compasslearning/javascript-style-guide](https://github.com/compasslearning/javascript-style-guide)
- - **DailyMotion**: [dailymotion/javascript](https://github.com/dailymotion/javascript)
- - **Digitpaint** [digitpaint/javascript](https://github.com/digitpaint/javascript)
- - **Evernote**: [evernote/javascript-style-guide](https://github.com/evernote/javascript-style-guide)
- - **ExactTarget**: [ExactTarget/javascript](https://github.com/ExactTarget/javascript)
- - **Flexberry**: [Flexberry/javascript-style-guide](https://github.com/Flexberry/javascript-style-guide)
- - **Gawker Media**: [gawkermedia/javascript](https://github.com/gawkermedia/javascript)
- - **General Electric**: [GeneralElectric/javascript](https://github.com/GeneralElectric/javascript)
- - **GoodData**: [gooddata/gdc-js-style](https://github.com/gooddata/gdc-js-style)
- - **Grooveshark**: [grooveshark/javascript](https://github.com/grooveshark/javascript)
- - **How About We**: [howaboutwe/javascript](https://github.com/howaboutwe/javascript)
- - **InfoJobs**: [InfoJobs/JavaScript-Style-Guide](https://github.com/InfoJobs/JavaScript-Style-Guide)
- - **Intent Media**: [intentmedia/javascript](https://github.com/intentmedia/javascript)
- - **Jam3**: [Jam3/Javascript-Code-Conventions](https://github.com/Jam3/Javascript-Code-Conventions)
- - **JSSolutions**: [JSSolutions/javascript](https://github.com/JSSolutions/javascript)
- - **Kinetica Solutions**: [kinetica/javascript](https://github.com/kinetica/javascript)
- - **Mighty Spring**: [mightyspring/javascript](https://github.com/mightyspring/javascript)
- - **MinnPost**: [MinnPost/javascript](https://github.com/MinnPost/javascript)
- - **ModCloth**: [modcloth/javascript](https://github.com/modcloth/javascript)
- - **Money Advice Service**: [moneyadviceservice/javascript](https://github.com/moneyadviceservice/javascript)
- - **Muber**: [muber/javascript](https://github.com/muber/javascript)
- - **National Geographic**: [natgeo/javascript](https://github.com/natgeo/javascript)
- - **National Park Service**: [nationalparkservice/javascript](https://github.com/nationalparkservice/javascript)
- - **Nimbl3**: [nimbl3/javascript](https://github.com/nimbl3/javascript)
- - **Nordic Venture Family**: [CodeDistillery/javascript](https://github.com/CodeDistillery/javascript)
- - **Orion Health**: [orionhealth/javascript](https://github.com/orionhealth/javascript)
- - **Peerby**: [Peerby/javascript](https://github.com/Peerby/javascript)
- - **Razorfish**: [razorfish/javascript-style-guide](https://github.com/razorfish/javascript-style-guide)
- - **reddit**: [reddit/styleguide/javascript](https://github.com/reddit/styleguide/tree/master/javascript)
- - **REI**: [reidev/js-style-guide](https://github.com/reidev/js-style-guide)
- - **Ripple**: [ripple/javascript-style-guide](https://github.com/ripple/javascript-style-guide)
- - **SeekingAlpha**: [seekingalpha/javascript-style-guide](https://github.com/seekingalpha/javascript-style-guide)
- - **Shutterfly**: [shutterfly/javascript](https://github.com/shutterfly/javascript)
- - **StudentSphere**: [studentsphere/javascript](https://github.com/studentsphere/javascript)
- - **Super**: [SuperJobs/javascript](https://github.com/SuperJobs/javascript)
- - **Target**: [target/javascript](https://github.com/target/javascript)
- - **TheLadders**: [TheLadders/javascript](https://github.com/TheLadders/javascript)
- - **T4R Technology**: [T4R-Technology/javascript](https://github.com/T4R-Technology/javascript)
- - **VoxFeed**: [VoxFeed/javascript-style-guide](https://github.com/VoxFeed/javascript-style-guide)
- - **Weggo**: [Weggo/javascript](https://github.com/Weggo/javascript)
- - **Zillow**: [zillow/javascript](https://github.com/zillow/javascript)
- - **ZocDoc**: [ZocDoc/javascript](https://github.com/ZocDoc/javascript)
-
-## Translation
-
- This style guide is also available in other languages:
-
- -  **Brazilian Portuguese**: [armoucar/javascript-style-guide](https://github.com/armoucar/javascript-style-guide)
- -  **Bulgarian**: [borislavvv/javascript](https://github.com/borislavvv/javascript)
- -  **Catalan**: [fpmweb/javascript-style-guide](https://github.com/fpmweb/javascript-style-guide)
- -  **Chinese(Traditional)**: [jigsawye/javascript](https://github.com/jigsawye/javascript)
- -  **Chinese(Simplified)**: [sivan/javascript-style-guide](https://github.com/sivan/javascript-style-guide)
- -  **French**: [nmussy/javascript-style-guide](https://github.com/nmussy/javascript-style-guide)
- -  **German**: [timofurrer/javascript-style-guide](https://github.com/timofurrer/javascript-style-guide)
- -  **Italian**: [sinkswim/javascript-style-guide](https://github.com/sinkswim/javascript-style-guide)
- -  **Japanese**: [mitsuruog/javacript-style-guide](https://github.com/mitsuruog/javacript-style-guide)
- -  **Korean**: [tipjs/javascript-style-guide](https://github.com/tipjs/javascript-style-guide)
- -  **Polish**: [mjurczyk/javascript](https://github.com/mjurczyk/javascript)
- -  **Russian**: [uprock/javascript](https://github.com/uprock/javascript)
- -  **Spanish**: [paolocarrasco/javascript-style-guide](https://github.com/paolocarrasco/javascript-style-guide)
- -  **Thai**: [lvarayut/javascript-style-guide](https://github.com/lvarayut/javascript-style-guide)
-
-## The JavaScript Style Guide Guide
-
- - [Reference](https://github.com/airbnb/javascript/wiki/The-JavaScript-Style-Guide-Guide)
-
-## Chat With Us About JavaScript
-
- - Find us on [gitter](https://gitter.im/airbnb/javascript).
-
-## Contributors
-
- - [View Contributors](https://github.com/airbnb/javascript/graphs/contributors)
-
-
-## License
-
-(The MIT License)
-
-Copyright (c) 2014 Airbnb
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-'Software'), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-**[⬆ back to top](#table-of-contents)**
-
-# };
diff --git a/linters/.eslintrc b/linters/.eslintrc.json
similarity index 79%
rename from linters/.eslintrc
rename to linters/.eslintrc.json
index 9e203a5473..6c30c4b3e8 100644
--- a/linters/.eslintrc
+++ b/linters/.eslintrc.json
@@ -1,5 +1,5 @@
-// Use this file as a starting point for your project's .eslintrc.
+// Use this file as a starting point for your project's .eslintrc.json.
// Copy this file, and add rule overrides as needed.
{
- "extends": "airbnb"
+ "extends": "ascribe"
}
diff --git a/linters/README.md b/linters/README.md
index 1deac701c7..755cf471d1 100644
--- a/linters/README.md
+++ b/linters/README.md
@@ -4,8 +4,10 @@ Our `.eslintrc` requires the following NPM packages:
```
npm install --save-dev \
- eslint-config-airbnb \
+ eslint-config-ascribe \
eslint \
babel-eslint \
- eslint-plugin-react
+ eslint-plugin-import \
+ eslint-plugin-react \
+ eslint-plugin-jsx-a11y
```
diff --git a/linters/SublimeLinter/SublimeLinter.sublime-settings b/linters/SublimeLinter/SublimeLinter.sublime-settings
deleted file mode 100644
index 12360f3f1c..0000000000
--- a/linters/SublimeLinter/SublimeLinter.sublime-settings
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
- * Airbnb JSHint settings for use with SublimeLinter and Sublime Text 2.
- *
- * 1. Install SublimeLinter at https://github.com/SublimeLinter/SublimeLinter
- * 2. Open user preferences for the SublimeLinter package in Sublime Text 2
- * * For Mac OS X go to _Sublime Text 2_ > _Preferences_ > _Package Settings_ > _SublimeLinter_ > _Settings - User_
- * 3. Paste the contents of this file into your settings file
- * 4. Save the settings file
- *
- * @version 0.3.0
- * @see https://github.com/SublimeLinter/SublimeLinter
- * @see http://www.jshint.com/docs/
- */
-{
- "jshint_options":
- {
- /*
- * ENVIRONMENTS
- * =================
- */
-
- // Define globals exposed by modern browsers.
- "browser": true,
-
- // Define globals exposed by jQuery.
- "jquery": true,
-
- // Define globals exposed by Node.js.
- "node": true,
-
- /*
- * ENFORCING OPTIONS
- * =================
- */
-
- // Force all variable names to use either camelCase style or UPPER_CASE
- // with underscores.
- "camelcase": true,
-
- // Prohibit use of == and != in favor of === and !==.
- "eqeqeq": true,
-
- // Suppress warnings about == null comparisons.
- "eqnull": true,
-
- // Enforce tab width of 2 spaces.
- "indent": 2,
-
- // Prohibit use of a variable before it is defined.
- "latedef": true,
-
- // Require capitalized names for constructor functions.
- "newcap": true,
-
- // Enforce use of single quotation marks for strings.
- "quotmark": "single",
-
- // Prohibit trailing whitespace.
- "trailing": true,
-
- // Prohibit use of explicitly undeclared variables.
- "undef": true,
-
- // Warn when variables are defined but never used.
- "unused": true,
-
- // Enforce line length to 80 characters
- "maxlen": 80,
-
- // Enforce placing 'use strict' at the top function scope
- "strict": true
- }
-}
diff --git a/linters/jshintrc b/linters/jshintrc
deleted file mode 100644
index 141067fd23..0000000000
--- a/linters/jshintrc
+++ /dev/null
@@ -1,62 +0,0 @@
-{
- /*
- * ENVIRONMENTS
- * =================
- */
-
- // Define globals exposed by modern browsers.
- "browser": true,
-
- // Define globals exposed by jQuery.
- "jquery": true,
-
- // Define globals exposed by Node.js.
- "node": true,
-
- // Allow ES6.
- "esnext": true,
-
- /*
- * ENFORCING OPTIONS
- * =================
- */
-
- // Force all variable names to use either camelCase style or UPPER_CASE
- // with underscores.
- "camelcase": true,
-
- // Prohibit use of == and != in favor of === and !==.
- "eqeqeq": true,
-
- // Enforce tab width of 2 spaces.
- "indent": 2,
-
- // Prohibit use of a variable before it is defined.
- "latedef": true,
-
- // Enforce line length to 80 characters
- "maxlen": 80,
-
- // Require capitalized names for constructor functions.
- "newcap": true,
-
- // Enforce use of single quotation marks for strings.
- "quotmark": "single",
-
- // Enforce placing 'use strict' at the top function scope
- "strict": true,
-
- // Prohibit use of explicitly undeclared variables.
- "undef": true,
-
- // Warn when variables are defined but never used.
- "unused": true,
-
- /*
- * RELAXING OPTIONS
- * =================
- */
-
- // Suppress warnings about == null comparisons.
- "eqnull": true
-}
diff --git a/package.json b/package.json
index dc0225dc08..8cc7c68ae3 100644
--- a/package.json
+++ b/package.json
@@ -1,18 +1,18 @@
{
- "name": "airbnb-style",
- "version": "2.0.0",
- "description": "A mostly reasonable approach to JavaScript.",
+ "name": "ascribe-style",
+ "version": "1.0.0",
+ "description": "A mostly reasonable approach to JavaScript, based off of Airbnb's styleguide.",
"scripts": {
- "test": "echo \"Error: no test specified\" && exit 1",
- "publish-all": "npm publish && cd ./packages/eslint-config-airbnb && npm publish"
+ "test": "echo \"Error: no test specified\""
},
"repository": {
"type": "git",
- "url": "https://github.com/airbnb/javascript.git"
+ "url": "https://github.com/ascribe/javascript.git"
},
"keywords": [
"style guide",
"lint",
+ "ascribe",
"airbnb",
"es6",
"es2015",
@@ -20,9 +20,27 @@
"jsx"
],
"author": "Harrison Shoff (https://twitter.com/hshoff)",
+ "contributors": [
+ {
+ "name": "Ascribe",
+ "url": "https://ascribe.io"
+ }
+ ],
"license": "MIT",
"bugs": {
- "url": "https://github.com/airbnb/javascript/issues"
+ "url": "https://github.com/ascribe/javascript/issues"
+ },
+ "homepage": "https://github.com/ascribe/javascript",
+ "dependencies": {
+ "eslint-config-airbnb": "^16.1.0",
+ "eslint-config-airbnb-base": "^12.1.0"
},
- "homepage": "https://github.com/airbnb/javascript"
+ "devDependencies": {
+ "babel-eslint": "^8.0.3",
+ "eslint": "^4.12.1",
+ "eslint-config-ascribe": "^3.0.4",
+ "eslint-plugin-import": "^2.8.0",
+ "eslint-plugin-jsx-a11y": "^6.0.2",
+ "eslint-plugin-react": "^7.5.1"
+ }
}
diff --git a/packages/eslint-config-airbnb/.eslintrc b/packages/eslint-config-airbnb/.eslintrc
deleted file mode 100644
index 4b3b1fa429..0000000000
--- a/packages/eslint-config-airbnb/.eslintrc
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "extends": "airbnb",
- "rules": {
- // disable requiring trailing commas because it might be nice to revert to
- // being JSON at some point, and I don't want to make big changes now.
- "comma-dangle": 0
- }
-}
diff --git a/packages/eslint-config-airbnb/README.md b/packages/eslint-config-airbnb/README.md
deleted file mode 100644
index f142c5a894..0000000000
--- a/packages/eslint-config-airbnb/README.md
+++ /dev/null
@@ -1,67 +0,0 @@
-# eslint-config-airbnb
-
-This package provides Airbnb's .eslintrc as an extensible shared config.
-
-## Usage
-
-We export three ESLint configurations for your usage.
-
-### eslint-config-airbnb
-
-Our default export contains all of our ESLint rules, including EcmaScript 6+
-and React. It requires `eslint`, `babel-eslint`, and `eslint-plugin-react`.
-
-1. `npm install --save-dev eslint-config-airbnb babel-eslint eslint-plugin-react eslint`
-2. add `"extends": "airbnb"` to your .eslintrc
-
-### eslint-config-airbnb/base
-
-Lints ES6+ but does not lint React. Requires `eslint` and `babel-eslint`.
-
-1. `npm install --save-dev eslint-config-airbnb babel-eslint eslint`
-2. add `"extends": "airbnb/base"` to your .eslintrc
-
-### eslint-config-airbnb/legacy
-
-Lints ES5 and below. Only requires `eslint`.
-
-1. `npm install --save-dev eslint-config-airbnb eslint`
-2. add `"extends": "airbnb/legacy"` to your .eslintrc
-
-See [Airbnb's Javascript styleguide](https://github.com/airbnb/javascript) and
-the [ESlint config docs](http://eslint.org/docs/user-guide/configuring#extending-configuration-files)
-for more information.
-
-## Improving this config
-
-Consider adding test cases if you're making complicated rules changes, like
-anything involving regexes. Perhaps in a distant future, we could use literate
-programming to structure our README as test cases for our .eslintrc?
-
-You can run tests with `npm test`.
-
-You can make sure this module lints with itself using `npm run lint`.
-
-## Changelog
-
-### 0.1.0
-
-- switch to modular rules files courtesy the [eslint-config-default][ecd]
- project and [@taion][taion]. [PR][pr-modular]
-- export `eslint-config-airbnb/legacy` for ES5-only users.
- `eslint-config-airbnb/legacy` does not require the `babel-eslint` parser.
- [PR][pr-legacy]
-
-[ecd]: https://github.com/walmartlabs/eslint-config-defaults
-[taion]: https://github.com/taion
-[pr-modular]: https://github.com/airbnb/javascript/pull/526
-[pr-legacy]: https://github.com/airbnb/javascript/pull/527
-
-### 0.0.9
-
-- add rule no-undef
-- add rule id-length
-
-### 0.0.8
- - now has a changelog
- - now is modular (see instructions above for with react and without react versions)
diff --git a/packages/eslint-config-airbnb/base.js b/packages/eslint-config-airbnb/base.js
deleted file mode 100644
index ff9904e775..0000000000
--- a/packages/eslint-config-airbnb/base.js
+++ /dev/null
@@ -1,8 +0,0 @@
-module.exports = {
- 'extends': [
- 'eslint-config-airbnb/legacy',
- 'eslint-config-airbnb/rules/es6',
- ],
- 'parser': 'babel-eslint',
- 'rules': {}
-};
diff --git a/packages/eslint-config-airbnb/index.js b/packages/eslint-config-airbnb/index.js
deleted file mode 100644
index 46d601fe3f..0000000000
--- a/packages/eslint-config-airbnb/index.js
+++ /dev/null
@@ -1,7 +0,0 @@
-module.exports = {
- 'extends': [
- 'eslint-config-airbnb/base',
- 'eslint-config-airbnb/rules/react',
- ],
- rules: {}
-};
diff --git a/packages/eslint-config-airbnb/legacy.js b/packages/eslint-config-airbnb/legacy.js
deleted file mode 100644
index 83a4931e84..0000000000
--- a/packages/eslint-config-airbnb/legacy.js
+++ /dev/null
@@ -1,21 +0,0 @@
-module.exports = {
- 'extends': [
- 'eslint-config-airbnb/rules/best-practices',
- 'eslint-config-airbnb/rules/errors',
- 'eslint-config-airbnb/rules/legacy',
- 'eslint-config-airbnb/rules/node',
- 'eslint-config-airbnb/rules/strict',
- 'eslint-config-airbnb/rules/style',
- 'eslint-config-airbnb/rules/variables'
- ],
- 'env': {
- 'browser': true,
- 'node': true,
- 'amd': false,
- 'mocha': false,
- 'jasmine': false
- },
- 'ecmaFeatures': {},
- 'globals': {},
- 'rules': {}
-};
diff --git a/packages/eslint-config-airbnb/node_modules/eslint-config-airbnb b/packages/eslint-config-airbnb/node_modules/eslint-config-airbnb
deleted file mode 120000
index a96aa0ea9d..0000000000
--- a/packages/eslint-config-airbnb/node_modules/eslint-config-airbnb
+++ /dev/null
@@ -1 +0,0 @@
-..
\ No newline at end of file
diff --git a/packages/eslint-config-airbnb/package.json b/packages/eslint-config-airbnb/package.json
deleted file mode 100644
index e7cd1bcc3c..0000000000
--- a/packages/eslint-config-airbnb/package.json
+++ /dev/null
@@ -1,36 +0,0 @@
-{
- "name": "eslint-config-airbnb",
- "version": "0.1.0",
- "description": "Airbnb's ESLint config, following our styleguide",
- "main": "index.js",
- "scripts": {
- "lint": "eslint .",
- "test": "babel-tape-runner ./test/test-*.js"
- },
- "repository": {
- "type": "git",
- "url": "https://github.com/airbnb/javascript"
- },
- "keywords": [
- "eslint",
- "eslintconfig",
- "config",
- "airbnb",
- "javascript",
- "styleguide"
- ],
- "author": "Jake Teton-Landis (https://twitter.com/@jitl)",
- "license": "MIT",
- "bugs": {
- "url": "https://github.com/airbnb/javascript/issues"
- },
- "homepage": "https://github.com/airbnb/javascript",
- "devDependencies": {
- "babel-eslint": "4.1.3",
- "babel-tape-runner": "1.2.0",
- "eslint": "1.5.1",
- "eslint-plugin-react": "3.4.2",
- "react": "0.13.3",
- "tape": "4.2.0"
- }
-}
diff --git a/packages/eslint-config-airbnb/rules/best-practices.js b/packages/eslint-config-airbnb/rules/best-practices.js
deleted file mode 100644
index 9d8199eb77..0000000000
--- a/packages/eslint-config-airbnb/rules/best-practices.js
+++ /dev/null
@@ -1,113 +0,0 @@
-module.exports = {
- 'rules': {
- // Enforces getter/setter pairs in objects
- 'accessor-pairs': 0,
- // treat var statements as if they were block scoped
- 'block-scoped-var': 2,
- // specify the maximum cyclomatic complexity allowed in a program
- 'complexity': [0, 11],
- // require return statements to either always or never specify values
- 'consistent-return': 2,
- // specify curly brace conventions for all control statements
- 'curly': [2, 'multi-line'],
- // require default case in switch statements
- 'default-case': 2,
- // encourages use of dot notation whenever possible
- 'dot-notation': [2, { 'allowKeywords': true}],
- // enforces consistent newlines before or after dots
- 'dot-location': 0,
- // require the use of === and !==
- 'eqeqeq': 2,
- // make sure for-in loops have an if statement
- 'guard-for-in': 2,
- // disallow the use of alert, confirm, and prompt
- 'no-alert': 1,
- // disallow use of arguments.caller or arguments.callee
- 'no-caller': 2,
- // disallow division operators explicitly at beginning of regular expression
- 'no-div-regex': 0,
- // disallow else after a return in an if
- 'no-else-return': 2,
- // disallow use of labels for anything other then loops and switches
- 'no-empty-label': 2,
- // disallow comparisons to null without a type-checking operator
- 'no-eq-null': 0,
- // disallow use of eval()
- 'no-eval': 2,
- // disallow adding to native types
- 'no-extend-native': 2,
- // disallow unnecessary function binding
- 'no-extra-bind': 2,
- // disallow fallthrough of case statements
- 'no-fallthrough': 2,
- // disallow the use of leading or trailing decimal points in numeric literals
- 'no-floating-decimal': 2,
- // disallow the type conversions with shorter notations
- 'no-implicit-coercion': 0,
- // disallow use of eval()-like methods
- 'no-implied-eval': 2,
- // disallow this keywords outside of classes or class-like objects
- 'no-invalid-this': 0,
- // disallow usage of __iterator__ property
- 'no-iterator': 2,
- // disallow use of labeled statements
- 'no-labels': 2,
- // disallow unnecessary nested blocks
- 'no-lone-blocks': 2,
- // disallow creation of functions within loops
- 'no-loop-func': 2,
- // disallow use of multiple spaces
- 'no-multi-spaces': 2,
- // disallow use of multiline strings
- 'no-multi-str': 2,
- // disallow reassignments of native objects
- 'no-native-reassign': 2,
- // disallow use of new operator when not part of the assignment or comparison
- 'no-new': 2,
- // disallow use of new operator for Function object
- 'no-new-func': 2,
- // disallows creating new instances of String,Number, and Boolean
- 'no-new-wrappers': 2,
- // disallow use of (old style) octal literals
- 'no-octal': 2,
- // disallow use of octal escape sequences in string literals, such as
- // var foo = 'Copyright \251';
- 'no-octal-escape': 2,
- // disallow reassignment of function parameters
- 'no-param-reassign': 2,
- // disallow use of process.env
- 'no-process-env': 0,
- // disallow usage of __proto__ property
- 'no-proto': 2,
- // disallow declaring the same variable more then once
- 'no-redeclare': 2,
- // disallow use of assignment in return statement
- 'no-return-assign': 2,
- // disallow use of `javascript:` urls.
- 'no-script-url': 2,
- // disallow comparisons where both sides are exactly the same
- 'no-self-compare': 2,
- // disallow use of comma operator
- 'no-sequences': 2,
- // restrict what can be thrown as an exception
- 'no-throw-literal': 2,
- // disallow usage of expressions in statement position
- 'no-unused-expressions': 2,
- // disallow unnecessary .call() and .apply()
- 'no-useless-call': 0,
- // disallow use of void operator
- 'no-void': 0,
- // disallow usage of configurable warning terms in comments: e.g. todo
- 'no-warning-comments': [0, { 'terms': ['todo', 'fixme', 'xxx'], 'location': 'start' }],
- // disallow use of the with statement
- 'no-with': 2,
- // require use of the second argument for parseInt()
- 'radix': 2,
- // requires to declare all vars on top of their containing scope
- 'vars-on-top': 2,
- // require immediate function invocation to be wrapped in parentheses
- 'wrap-iife': [2, 'any'],
- // require or disallow Yoda conditions
- 'yoda': 2
- }
-};
diff --git a/packages/eslint-config-airbnb/rules/errors.js b/packages/eslint-config-airbnb/rules/errors.js
deleted file mode 100644
index ec1b1aab0e..0000000000
--- a/packages/eslint-config-airbnb/rules/errors.js
+++ /dev/null
@@ -1,60 +0,0 @@
-module.exports = {
- 'rules': {
- // disallow trailing commas in object literals
- 'comma-dangle': [2, 'always-multiline'],
- // disallow assignment in conditional expressions
- 'no-cond-assign': [2, 'always'],
- // disallow use of console
- 'no-console': 1,
- // disallow use of constant expressions in conditions
- 'no-constant-condition': 1,
- // disallow control characters in regular expressions
- 'no-control-regex': 2,
- // disallow use of debugger
- 'no-debugger': 1,
- // disallow duplicate arguments in functions
- 'no-dupe-args': 2,
- // disallow duplicate keys when creating object literals
- 'no-dupe-keys': 2,
- // disallow a duplicate case label.
- 'no-duplicate-case': 2,
- // disallow the use of empty character classes in regular expressions
- 'no-empty-character-class': 2,
- // disallow empty statements
- 'no-empty': 2,
- // disallow assigning to the exception in a catch block
- 'no-ex-assign': 2,
- // disallow double-negation boolean casts in a boolean context
- 'no-extra-boolean-cast': 0,
- // disallow unnecessary parentheses
- 'no-extra-parens': [2, 'functions'],
- // disallow unnecessary semicolons
- 'no-extra-semi': 2,
- // disallow overwriting functions written as function declarations
- 'no-func-assign': 2,
- // disallow function or variable declarations in nested blocks
- 'no-inner-declarations': 2,
- // disallow invalid regular expression strings in the RegExp constructor
- 'no-invalid-regexp': 2,
- // disallow irregular whitespace outside of strings and comments
- 'no-irregular-whitespace': 2,
- // disallow negation of the left operand of an in expression
- 'no-negated-in-lhs': 2,
- // disallow the use of object properties of the global object (Math and JSON) as functions
- 'no-obj-calls': 2,
- // disallow multiple spaces in a regular expression literal
- 'no-regex-spaces': 2,
- // disallow sparse arrays
- 'no-sparse-arrays': 2,
- // disallow unreachable statements after a return, throw, continue, or break statement
- 'no-unreachable': 2,
- // disallow comparisons with the value NaN
- 'use-isnan': 2,
- // ensure JSDoc comments are valid
- 'valid-jsdoc': 0,
- // ensure that the results of typeof are compared against a valid string
- 'valid-typeof': 2,
- // Avoid code that looks like two expressions but is actually one
- 'no-unexpected-multiline': 0
- }
-};
diff --git a/packages/eslint-config-airbnb/rules/es6.js b/packages/eslint-config-airbnb/rules/es6.js
deleted file mode 100644
index b672d4aae1..0000000000
--- a/packages/eslint-config-airbnb/rules/es6.js
+++ /dev/null
@@ -1,51 +0,0 @@
-module.exports = {
- 'env': {
- 'es6': false
- },
- 'ecmaFeatures': {
- 'arrowFunctions': true,
- 'blockBindings': true,
- 'classes': true,
- 'defaultParams': true,
- 'destructuring': true,
- 'forOf': true,
- 'generators': false,
- 'modules': true,
- 'objectLiteralComputedProperties': true,
- 'objectLiteralDuplicateProperties': false,
- 'objectLiteralShorthandMethods': true,
- 'objectLiteralShorthandProperties': true,
- 'spread': true,
- 'superInFunctions': true,
- 'templateStrings': true,
- 'jsx': true
- },
- 'rules': {
- // require parens in arrow function arguments
- 'arrow-parens': 0,
- // require space before/after arrow function's arrow
- 'arrow-spacing': 0,
- // verify super() callings in constructors
- 'constructor-super': 0,
- // enforce the spacing around the * in generator functions
- 'generator-star-spacing': 0,
- // disallow modifying variables of class declarations
- 'no-class-assign': 0,
- // disallow modifying variables that are declared using const
- 'no-const-assign': 0,
- // disallow to use this/super before super() calling in constructors.
- 'no-this-before-super': 0,
- // require let or const instead of var
- 'no-var': 2,
- // require method and property shorthand syntax for object literals
- 'object-shorthand': 0,
- // suggest using of const declaration for variables that are never modified after declared
- 'prefer-const': 2,
- // suggest using the spread operator instead of .apply()
- 'prefer-spread': 0,
- // suggest using Reflect methods where applicable
- 'prefer-reflect': 0,
- // disallow generator functions that do not have yield
- 'require-yield': 0
- }
-};
diff --git a/packages/eslint-config-airbnb/rules/legacy.js b/packages/eslint-config-airbnb/rules/legacy.js
deleted file mode 100644
index 1d0c518316..0000000000
--- a/packages/eslint-config-airbnb/rules/legacy.js
+++ /dev/null
@@ -1,16 +0,0 @@
-module.exports = {
- 'rules': {
- // specify the maximum depth that blocks can be nested
- 'max-depth': [0, 4],
- // specify the maximum length of a line in your program
- 'max-len': [0, 80, 4],
- // limits the number of parameters that can be used in the function declaration.
- 'max-params': [0, 3],
- // specify the maximum number of statement allowed in a function
- 'max-statements': [0, 10],
- // disallow use of bitwise operators
- 'no-bitwise': 0,
- // disallow use of unary operators, ++ and --
- 'no-plusplus': 0
- }
-};
diff --git a/packages/eslint-config-airbnb/rules/node.js b/packages/eslint-config-airbnb/rules/node.js
deleted file mode 100644
index 16b6f20d45..0000000000
--- a/packages/eslint-config-airbnb/rules/node.js
+++ /dev/null
@@ -1,23 +0,0 @@
-module.exports = {
- 'env': {
- 'node': true
- },
- 'rules': {
- // enforce return after a callback
- 'callback-return': 0,
- // enforces error handling in callbacks (node environment)
- 'handle-callback-err': 0,
- // disallow mixing regular variable and require declarations
- 'no-mixed-requires': [0, false],
- // disallow use of new operator with the require function
- 'no-new-require': 0,
- // disallow string concatenation with __dirname and __filename
- 'no-path-concat': 0,
- // disallow process.exit()
- 'no-process-exit': 0,
- // restrict usage of specified node modules
- 'no-restricted-modules': 0,
- // disallow use of synchronous methods (off by default)
- 'no-sync': 0
- }
-};
diff --git a/packages/eslint-config-airbnb/rules/react.js b/packages/eslint-config-airbnb/rules/react.js
deleted file mode 100644
index 01aa64c30a..0000000000
--- a/packages/eslint-config-airbnb/rules/react.js
+++ /dev/null
@@ -1,62 +0,0 @@
-module.exports = {
- 'parser': 'babel-eslint',
- 'plugins': [
- 'react'
- ],
- 'ecmaFeatures': {
- 'jsx': true
- },
- 'rules': {
- // Prevent missing displayName in a React component definition
- 'react/display-name': 0,
- // Enforce boolean attributes notation in JSX
- 'react/jsx-boolean-value': 2,
- // Enforce or disallow spaces inside of curly braces in JSX attributes
- 'react/jsx-curly-spacing': 0,
- // Prevent duplicate props in JSX
- 'react/jsx-no-duplicate-props': 0,
- // Disallow undeclared variables in JSX
- 'react/jsx-no-undef': 2,
- // Enforce quote style for JSX attributes
- 'react/jsx-quotes': 0,
- // Enforce propTypes declarations alphabetical sorting
- 'react/jsx-sort-prop-types': 0,
- // Enforce props alphabetical sorting
- 'react/jsx-sort-props': 0,
- // Prevent React to be incorrectly marked as unused
- 'react/jsx-uses-react': 2,
- // Prevent variables used in JSX to be incorrectly marked as unused
- 'react/jsx-uses-vars': 2,
- // Prevent usage of dangerous JSX properties
- 'react/no-danger': 0,
- // Prevent usage of setState in componentDidMount
- 'react/no-did-mount-set-state': [2, 'allow-in-func'],
- // Prevent usage of setState in componentDidUpdate
- 'react/no-did-update-set-state': 2,
- // Prevent multiple component definition per file
- 'react/no-multi-comp': 2,
- // Prevent usage of unknown DOM property
- 'react/no-unknown-property': 2,
- // Prevent missing props validation in a React component definition
- 'react/prop-types': 2,
- // Prevent missing React when using JSX
- 'react/react-in-jsx-scope': 2,
- // Restrict file extensions that may be required
- 'react/require-extension': 0,
- // Prevent extra closing tags for components without children
- 'react/self-closing-comp': 2,
- // Enforce component methods order
- 'react/sort-comp': [2, {
- 'order': [
- 'lifecycle',
- '/^on.+$/',
- '/^(get|set)(?!(InitialState$|DefaultProps$|ChildContext$)).+$/',
- 'everything-else',
- '/^render.+$/',
- 'render'
- ]
- }],
- // Prevent missing parentheses around multilines JSX
- 'react/wrap-multilines': 2
- }
-};
diff --git a/packages/eslint-config-airbnb/rules/strict.js b/packages/eslint-config-airbnb/rules/strict.js
deleted file mode 100644
index 6d32f8ca59..0000000000
--- a/packages/eslint-config-airbnb/rules/strict.js
+++ /dev/null
@@ -1,6 +0,0 @@
-module.exports = {
- 'rules': {
- // babel inserts `'use strict';` for us
- 'strict': [2, 'never']
- }
-};
diff --git a/packages/eslint-config-airbnb/rules/style.js b/packages/eslint-config-airbnb/rules/style.js
deleted file mode 100644
index fa22403d8b..0000000000
--- a/packages/eslint-config-airbnb/rules/style.js
+++ /dev/null
@@ -1,113 +0,0 @@
-module.exports = {
- 'rules': {
- // enforce spacing inside array brackets
- 'array-bracket-spacing': 0,
- // enforce one true brace style
- 'brace-style': [2, '1tbs', {'allowSingleLine': true }],
- // require camel case names
- 'camelcase': [2, {'properties': 'never'}],
- // enforce spacing before and after comma
- 'comma-spacing': [2, {'before': false, 'after': true}],
- // enforce one true comma style
- 'comma-style': [2, 'last'],
- // require or disallow padding inside computed properties
- 'computed-property-spacing': 0,
- // enforces consistent naming when capturing the current execution context
- 'consistent-this': 0,
- // enforce newline at the end of file, with no multiple empty lines
- 'eol-last': 2,
- // require function expressions to have a name
- 'func-names': 1,
- // enforces use of function declarations or expressions
- 'func-style': 0,
- // this option enforces minimum and maximum identifier lengths (variable names, property names etc.)
- 'id-length': [2, {'min': 2, 'properties': 'never'}],
- // this option sets a specific tab width for your code
- 'indent': [2, 2],
- // specify whether double or single quotes should be used in JSX attributes
- 'jsx-quotes': 2,
- // enforces spacing between keys and values in object literal properties
- 'key-spacing': [2, {'beforeColon': false, 'afterColon': true}],
- // enforces empty lines around comments
- 'lines-around-comment': 0,
- // disallow mixed 'LF' and 'CRLF' as linebreaks
- 'linebreak-style': 0,
- // specify the maximum depth callbacks can be nested
- 'max-nested-callbacks': 0,
- // require a capital letter for constructors
- 'new-cap': [2, {'newIsCap': true}],
- // disallow the omission of parentheses when invoking a constructor with no arguments
- 'new-parens': 0,
- // allow/disallow an empty newline after var statement
- 'newline-after-var': 0,
- // disallow use of the Array constructor
- 'no-array-constructor': 0,
- // disallow use of the continue statement
- 'no-continue': 0,
- // disallow comments inline after code
- 'no-inline-comments': 0,
- // disallow if as the only statement in an else block
- 'no-lonely-if': 0,
- // disallow mixed spaces and tabs for indentation
- 'no-mixed-spaces-and-tabs': 0,
- // disallow multiple empty lines
- 'no-multiple-empty-lines': [2, {'max': 2}],
- // disallow nested ternary expressions
- 'no-nested-ternary': 2,
- // disallow use of the Object constructor
- 'no-new-object': 2,
- // disallow space between function identifier and application
- 'no-spaced-func': 2,
- // disallow the use of ternary operators
- 'no-ternary': 0,
- // disallow trailing whitespace at the end of lines
- 'no-trailing-spaces': 2,
- // disallow dangling underscores in identifiers
- 'no-underscore-dangle': 0,
- // disallow the use of Boolean literals in conditional expressions
- 'no-unneeded-ternary': 0,
- // require or disallow padding inside curly braces
- 'object-curly-spacing': 0,
- // allow just one var statement per function
- 'one-var': [2, 'never'],
- // require assignment operator shorthand where possible or prohibit it entirely
- 'operator-assignment': 0,
- // enforce operators to be placed before or after line breaks
- 'operator-linebreak': 0,
- // enforce padding within blocks
- 'padded-blocks': [2, 'never'],
- // require quotes around object literal property names
- 'quote-props': 0,
- // specify whether double or single quotes should be used
- 'quotes': [2, 'single', 'avoid-escape'],
- // require identifiers to match the provided regular expression
- 'id-match': 0,
- // enforce spacing before and after semicolons
- 'semi-spacing': [2, {'before': false, 'after': true}],
- // require or disallow use of semicolons instead of ASI
- 'semi': [2, 'always'],
- // sort variables within the same declaration block
- 'sort-vars': 0,
- // require a space after certain keywords
- 'space-after-keywords': 2,
- // require or disallow space before blocks
- 'space-before-blocks': 2,
- // require or disallow space before function opening parenthesis
- 'space-before-function-paren': [2, 'never'],
- // require or disallow spaces inside parentheses
- 'space-in-parens': 0,
- // require spaces around operators
- 'space-infix-ops': 2,
- // require a space after return, throw, and case
- 'space-return-throw-case': 2,
- // Require or disallow spaces before/after unary operators
- 'space-unary-ops': 0,
- // require or disallow a space immediately following the // or /* in a comment
- 'spaced-comment': [2, 'always', {
- 'exceptions': ['-', '+'],
- 'markers': ['=', '!'] // space here to support sprockets directives
- }],
- // require regex literals to be wrapped in parentheses
- 'wrap-regex': 0
- }
-};
diff --git a/packages/eslint-config-airbnb/rules/variables.js b/packages/eslint-config-airbnb/rules/variables.js
deleted file mode 100644
index 3da93fe826..0000000000
--- a/packages/eslint-config-airbnb/rules/variables.js
+++ /dev/null
@@ -1,26 +0,0 @@
-module.exports = {
- 'rules': {
- // enforce or disallow variable initializations at definition
- 'init-declarations': 0,
- // disallow the catch clause parameter name being the same as a variable in the outer scope
- 'no-catch-shadow': 0,
- // disallow deletion of variables
- 'no-delete-var': 2,
- // disallow labels that share a name with a variable
- 'no-label-var': 0,
- // disallow shadowing of names such as arguments
- 'no-shadow-restricted-names': 2,
- // disallow declaration of variables already declared in the outer scope
- 'no-shadow': 2,
- // disallow use of undefined when initializing variables
- 'no-undef-init': 0,
- // disallow use of undeclared variables unless mentioned in a /*global */ block
- 'no-undef': 2,
- // disallow use of undefined variable
- 'no-undefined': 0,
- // disallow declaration of variables that are not used in the code
- 'no-unused-vars': [2, {'vars': 'local', 'args': 'after-used'}],
- // disallow use of variables before they are defined
- 'no-use-before-define': 2
- }
-};
diff --git a/packages/eslint-config-airbnb/test/.eslintrc b/packages/eslint-config-airbnb/test/.eslintrc
deleted file mode 100644
index 7f79874e41..0000000000
--- a/packages/eslint-config-airbnb/test/.eslintrc
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "rules": {
- // disabled because I find it tedious to write tests while following this
- // rule
- "no-shadow": 0,
- // tests uses `t` for tape
- "id-length": [2, {"min": 2, "properties": "never", "exceptions": ["t"]}]
- }
-}
diff --git a/packages/eslint-config-airbnb/test/test-base.js b/packages/eslint-config-airbnb/test/test-base.js
deleted file mode 100644
index 24aa884cd0..0000000000
--- a/packages/eslint-config-airbnb/test/test-base.js
+++ /dev/null
@@ -1,30 +0,0 @@
-import fs from 'fs';
-import path from 'path';
-import test from 'tape';
-
-const files = {
- base: require('../base')
-};
-
-fs.readdirSync(path.join(__dirname, '../rules')).forEach(name => {
- if (name === 'react.js') {
- return;
- }
-
- files[name] = require(`../rules/${name}`);
-});
-
-Object.keys(files).forEach(name => {
- const config = files[name];
-
- test(`${name}: does not reference react`, t => {
- t.plan(2);
-
- t.notOk(config.plugins, 'plugins is unspecified');
-
- // scan rules for react/ and fail if any exist
- const reactRuleIds = Object.keys(config.rules)
- .filter(ruleId => ruleId.indexOf('react/') === 0);
- t.deepEquals(reactRuleIds, [], 'there are no react/ rules');
- });
-});
diff --git a/packages/eslint-config-airbnb/test/test-react-order.js b/packages/eslint-config-airbnb/test/test-react-order.js
deleted file mode 100644
index 606f723671..0000000000
--- a/packages/eslint-config-airbnb/test/test-react-order.js
+++ /dev/null
@@ -1,88 +0,0 @@
-import test from 'tape';
-import { CLIEngine } from 'eslint';
-import eslintrc from '../';
-import baseConfig from '../base';
-import reactRules from '../rules/react';
-
-const cli = new CLIEngine({
- useEslintrc: false,
- baseConfig: eslintrc,
-
- // This rule fails when executing on text.
- rules: {indent: 0},
-});
-
-function lint(text) {
- // @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeonfiles
- // @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeontext
- return cli.executeOnText(text).results[0];
-}
-
-function wrapComponent(body) {
- return `
-import React from 'react';
-export default class MyComponent extends React.Component {
-${body}
-}
-`;
-}
-
-test('validate react prop order', t => {
- t.test('make sure our eslintrc has React linting dependencies', t => {
- t.plan(2);
- t.equal(baseConfig.parser, 'babel-eslint', 'uses babel-eslint');
- t.equal(reactRules.plugins[0], 'react', 'uses eslint-plugin-react');
- });
-
- t.test('passes a good component', t => {
- t.plan(3);
- const result = lint(wrapComponent(`
- componentWillMount() {}
- componentDidMount() {}
- setFoo() {}
- getFoo() {}
- setBar() {}
- someMethod() {}
- renderDogs() {}
- render() { return ; }
-`));
-
- t.notOk(result.warningCount, 'no warnings');
- t.notOk(result.errorCount, 'no errors');
- t.deepEquals(result.messages, [], 'no messages in results');
- });
-
- t.test('order: when random method is first', t => {
- t.plan(2);
- const result = lint(wrapComponent(`
- someMethod() {}
- componentWillMount() {}
- componentDidMount() {}
- setFoo() {}
- getFoo() {}
- setBar() {}
- renderDogs() {}
- render() { return ; }
-`));
-
- t.ok(result.errorCount, 'fails');
- t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort');
- });
-
- t.test('order: when random method after lifecycle methods', t => {
- t.plan(2);
- const result = lint(wrapComponent(`
- componentWillMount() {}
- componentDidMount() {}
- someMethod() {}
- setFoo() {}
- getFoo() {}
- setBar() {}
- renderDogs() {}
- render() { return ; }
-`));
-
- t.ok(result.errorCount, 'fails');
- t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort');
- });
-});
diff --git a/packages/eslint-config-ascribe-react/README.md b/packages/eslint-config-ascribe-react/README.md
new file mode 100644
index 0000000000..2587294606
--- /dev/null
+++ b/packages/eslint-config-ascribe-react/README.md
@@ -0,0 +1,50 @@
+eslint-config-ascribe-react
+---------------------------
+
+[](https://www.npmjs.com/package/eslint-config-ascribe-react)
+
+> Provides a React + ES6 [ESLint](http://eslint.org/) configuration against [Ascribe's JavaScript style guide](https://github.com/ascribe/javascript).
+
+As Airbnb graciously provides a default ESLint configuration (see [here](https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb)), we extend that and override it when our rules differ (for ES6 rules, we pass through the extended rules from our base [eslint-config-ascribe](https://github.com/ascribe/javascript/tree/master/packages/eslint-config-ascribe) config).
+
+## Installation
+
+```bash
+npm install --save-dev eslint-config-ascribe-react babel-eslint eslint-plugin-import eslint-plugin-react eslint-plugin-jsx-a11y eslint
+```
+
+Two configurations are exported:
+
+### eslint-config-ascribe-react
+
+Includes both ES6 and React configurations. To use, add `"extends": "ascribe-react"` to your ESLint configuration:
+
+```json
+{
+ "extends": "ascribe-react"
+}
+```
+
+### eslint-config-ascribe-react/react-only
+
+Includes just the React configuration. To use, add `"extends": "ascribe-react/react-only"` to your ESLint configuration:
+
+```json
+{
+ "extends": "ascribe-react/react-only"
+}
+```
+
+## npm releases
+
+Since this package is part of our styleguide repo, automating npm releases is tricky (can't have multiple Git tags in one repo etc.).
+
+So for now it's all manual. Make sure to actually publish the respective package folder, not the whole repo by going into the package folder first:
+
+```bash
+cd packages/eslint-config-ascribe-react
+
+# update version number in package.json, then:
+git commit -am "Release 2.0.2"
+npm publish
+```
\ No newline at end of file
diff --git a/packages/eslint-config-ascribe-react/index.js b/packages/eslint-config-ascribe-react/index.js
new file mode 100644
index 0000000000..58587af729
--- /dev/null
+++ b/packages/eslint-config-ascribe-react/index.js
@@ -0,0 +1,11 @@
+customRulesReact = require('./rules/custom_react.js');
+customSettingsReact = require('./settings/custom_react.js');
+
+module.exports = {
+ extends: [
+ 'airbnb',
+ 'ascribe',
+ ],
+ rules: Object.assign({}, customRulesReact),
+ settings: Object.assign({}, customSettingsReact),
+};
diff --git a/packages/eslint-config-ascribe-react/package.json b/packages/eslint-config-ascribe-react/package.json
new file mode 100644
index 0000000000..7587b605ab
--- /dev/null
+++ b/packages/eslint-config-ascribe-react/package.json
@@ -0,0 +1,46 @@
+{
+ "name": "eslint-config-ascribe-react",
+ "version": "2.0.4",
+ "description": "Ascribe's React ESLint config, following our styleguide",
+ "main": "index.js",
+ "scripts": {},
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/ascribe/javascript"
+ },
+ "keywords": [
+ "airbnb",
+ "ascribe",
+ "config",
+ "eslint",
+ "eslintconfig",
+ "eslint-config",
+ "javascript",
+ "react",
+ "styleguide"
+ ],
+ "author": "Ascribe",
+ "license": "Apache-2.0",
+ "bugs": {
+ "url": "https://github.com/ascribe/javascript/issues"
+ },
+ "homepage": "https://github.com/ascribe/javascript",
+ "dependencies": {
+ "eslint-config-airbnb": "^16.1.0",
+ "eslint-config-ascribe": "^3.0.4"
+ },
+ "peerDependencies": {
+ "babel-eslint": "^8.0.3",
+ "eslint": "^4.12.1",
+ "eslint-plugin-import": "^2.8.0",
+ "eslint-plugin-jsx-a11y": "^6.0.2",
+ "eslint-plugin-react": "^7.5.1"
+ },
+ "devDependencies": {
+ "babel-eslint": "^8.0.3",
+ "eslint": "^4.12.1",
+ "eslint-plugin-import": "^2.8.0",
+ "eslint-plugin-jsx-a11y": "^6.0.2",
+ "eslint-plugin-react": "^7.5.1"
+ }
+}
diff --git a/packages/eslint-config-ascribe-react/react-only.js b/packages/eslint-config-ascribe-react/react-only.js
new file mode 100644
index 0000000000..65bc6e5151
--- /dev/null
+++ b/packages/eslint-config-ascribe-react/react-only.js
@@ -0,0 +1,12 @@
+base = require('eslint-config-ascribe/base.js');
+customRulesReact = require('./rules/custom_react.js');
+
+module.exports = Object.assign(base, {
+ extends: [
+ 'airbnb/rules/react',
+ 'airbnb/rules/react-a11y',
+ ],
+
+ parser: 'babel-eslint',
+ rules: customRulesReact,
+});
diff --git a/packages/eslint-config-ascribe-react/rules/custom_react.js b/packages/eslint-config-ascribe-react/rules/custom_react.js
new file mode 100644
index 0000000000..82731ecfc8
--- /dev/null
+++ b/packages/eslint-config-ascribe-react/rules/custom_react.js
@@ -0,0 +1,139 @@
+// Export React rule overrides against default Airbnb's
+module.exports = {
+
+ /**
+ * React
+ * https://github.com/yannickcr/eslint-plugin-react#list-of-supported-rules
+ */
+
+ // Warn on certain propTypes (any, array, object)
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-prop-types.md
+ 'react/forbid-prop-types': [1, { forbid: ['any', 'array', 'object'] }],
+
+ // Prevent usage of dangerous JSX properties
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-danger.md
+ 'react/no-danger': 2,
+
+ // Prevent direct mutation of this.state
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-direct-mutation-state.md
+ 'react/no-direct-mutation-state': 2,
+
+ // Warn on multiple component definition per file
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-multi-comp.md
+ 'react/no-multi-comp': [1, { 'ignoreStateless': true }],
+
+ // Require React.createClass declarations over ES6 classes
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-es6-class.md
+ 'react/prefer-es6-class': [2, 'never'],
+
+ // Warn on components that could be made stateless
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-stateless-function.md
+ 'react/prefer-stateless-function': 2,
+
+ // Reset deprecated require-extension rule
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-extension.md/
+ 'react/require-extension': 0,
+
+ // Enforce component methods order
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-comp.md
+ 'react/sort-comp': [2, {
+ 'order': [
+ 'static-methods',
+ 'lifecycle',
+ 'everything-else',
+ '/^render.+$/',
+ 'render'
+ ],
+ }],
+
+ // Enforce grouping requireds and alphabetical sorting of propType declarations
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-prop-types.md
+ 'react/sort-prop-types': [2, {
+ 'ignoreCase': true,
+ 'callbacksLast': false,
+ 'requiredFirst': true
+ }],
+
+
+ /**
+ * JSX
+ * https://github.com/yannickcr/eslint-plugin-react#jsx-specific-rules
+ */
+
+ // Validate closing bracket location in JSX
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-closing-bracket-location.md
+ 'react/jsx-closing-bracket-location': [2, 'after-props'],
+
+ // Enforce JSX files to have .js extension
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-filename-extension.md
+ 'react/jsx-filename-extension': [2, { extensions: ['.js'] }],
+
+ // Enforce JSX indentation
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-indent.md
+ 'react/jsx-indent': [2, 4],
+
+ // Validate props indentation in JSX
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-indent-props.md
+ 'react/jsx-indent-props': [2, 4],
+
+ // Validate JSX has key prop when in array or iterator
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-key.md
+ 'react/jsx-key': 1,
+
+ // Prevent duplicate props in JSX
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-duplicate-props.md
+ 'react/jsx-no-duplicate-props': [2, { 'ignoreCase': false }],
+
+ // Disallow unsafe target="_blank" on links
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-target-blank.md
+ 'react/jsx-no-target-blank': 2,
+
+ // Enforce props alphabetical sorting
+ // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-props.md
+ 'react/jsx-sort-props': [2, {
+ 'ignoreCase': true,
+ 'callbacksLast': false,
+ 'shorthandFirst': true
+ }],
+
+
+ /**
+ * JSX A11Y
+ * https://github.com/evcohen/eslint-plugin-jsx-a11y#supported-rules
+ */
+
+ // Enforce all aria-* props are valid.
+ // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-props.md
+ 'jsx-a11y/aria-props': 2,
+
+ // Enforce ARIA state and property values are valid.
+ // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-proptypes.md
+ 'jsx-a11y/aria-proptypes': 2,
+
+ // Require ARIA roles to be valid and non-abstract
+ // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-role.md
+ 'jsx-a11y/aria-role': 2,
+
+ // Enforce that elements that do not support ARIA roles, states, and properties do not have
+ // those attributes.
+ // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-unsupported-elements.md
+ 'jsx-a11y/aria-unsupported-elements': 2,
+
+ // Require that labels use "htmlFor"
+ // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/label-has-for.md
+ 'jsx-a11y/label-has-for': 2,
+
+ // Enforce that elements with onClick handlers must be focusable.
+ // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/interactive-supports-focus.md
+ 'jsx-a11y/interactive-supports-focus': 2,
+
+ // Enforce that elements with ARIA roles must have all required attributes for that role.
+ // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/role-has-required-aria-props.md
+ 'jsx-a11y/role-has-required-aria-props': 2,
+
+ // Enforce that elements with explicit or implicit roles defined contain
+ // only aria-* properties supported by that role.
+ // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/role-supports-aria-props.md
+ 'jsx-a11y/role-supports-aria-props': 2,
+
+};
diff --git a/packages/eslint-config-ascribe-react/settings/custom_react.js b/packages/eslint-config-ascribe-react/settings/custom_react.js
new file mode 100644
index 0000000000..18087f0e7f
--- /dev/null
+++ b/packages/eslint-config-ascribe-react/settings/custom_react.js
@@ -0,0 +1,5 @@
+module.exports = {
+ "react": {
+ "version": "15.0"
+ }
+}
diff --git a/packages/eslint-config-ascribe/README.md b/packages/eslint-config-ascribe/README.md
new file mode 100644
index 0000000000..653888a8ad
--- /dev/null
+++ b/packages/eslint-config-ascribe/README.md
@@ -0,0 +1,57 @@
+eslint-config-ascribe
+---------------------
+
+[](https://www.npmjs.com/package/eslint-config-ascribe)
+
+> Provides a ES6 [ESLint](http://eslint.org/) configuration against [Ascribe's JavaScript style guide](https://github.com/ascribe/javascript).
+
+As Airbnb graciously provides a default ES6 ESLint configuration (see [here](https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb-base)), we extend that and override it when our rules differ.
+
+
+## Installation
+
+```bash
+npm install --save-dev eslint-config-ascribe babel-eslint eslint-plugin-import eslint
+```
+
+Two configurations are exported:
+
+### eslint-config-ascribe
+
+Full ES6 configuration. Like airbnb's, it requires `eslint` and `eslint-plugin-import`, but also
+`babel-eslint` for some ES6+ features that ESLint doesn't natively know about yet. To use, add `"extends": "ascribe"` to your ESLint configuration:
+
+```json
+{
+ "extends": "ascribe"
+}
+```
+
+### eslint-config-ascribe/es5
+
+Same as the full configuration, except with all ES6 features turned off and uses ESLint's default
+parser.
+
+To use:
+
+* Add `"extends": "ascribe/es5"` to your ESLint configuration:
+
+```json
+{
+ "extends": "ascribe/es5"
+}
+```
+
+## npm releases
+
+Since this package is part of our styleguide repo, automating npm releases is tricky (can't have multiple Git tags in one repo etc.).
+
+So for now it's all manual. Make sure to actually publish the respective package folder, not the whole repo by going into the package folder first:
+
+```bash
+cd packages/eslint-config-ascribe
+
+# update version number in package.json, then:
+git commit -am "Release 3.0.2"
+npm publish
+```
diff --git a/packages/eslint-config-ascribe/base.js b/packages/eslint-config-ascribe/base.js
new file mode 100644
index 0000000000..c50af4ddbb
--- /dev/null
+++ b/packages/eslint-config-ascribe/base.js
@@ -0,0 +1,18 @@
+module.exports = {
+ env: {
+ browser: true,
+ node: true,
+ },
+ parserOptions: {
+ ecmaVersion: 2017,
+ sourceType: 'module',
+ },
+ globals: {
+ // Disable overwriting for commonly used polyfills
+ 'fetch': false,
+ 'Promise': false,
+
+ // Use process for environment variables (ie. NODE_ENV)
+ 'process': false,
+ }
+};
diff --git a/packages/eslint-config-ascribe/es5.js b/packages/eslint-config-ascribe/es5.js
new file mode 100644
index 0000000000..7b02d376c3
--- /dev/null
+++ b/packages/eslint-config-ascribe/es5.js
@@ -0,0 +1,16 @@
+base = require('./base.js');
+
+customRules = require('./rules/custom.js');
+noEs6Rules = require('./rules/no-es6.js');
+
+// Remove ES6-specifics from base config
+base.parserOptions.ecmaVersion = 5;
+delete base.globals.fetch;
+delete base.globals.Promise;
+
+
+module.exports = Object.assign(base, {
+ extends: 'airbnb-base',
+
+ rules: Object.assign({}, customRules, noEs6Rules),
+});
diff --git a/packages/eslint-config-ascribe/index.js b/packages/eslint-config-ascribe/index.js
new file mode 100644
index 0000000000..c938a73363
--- /dev/null
+++ b/packages/eslint-config-ascribe/index.js
@@ -0,0 +1,15 @@
+base = require('./base.js');
+
+customRules = require('./rules/custom.js');
+customRulesImport = require('./rules/custom_import.js');
+
+customSettingsImport = require('./settings/custom_import.js');
+
+module.exports = Object.assign(base, {
+ extends: 'airbnb-base',
+ parser: 'babel-eslint',
+
+ // Airbnb-base already requires import plugin
+ rules: Object.assign({}, customRules, customRulesImport),
+ settings: Object.assign({}, customSettingsImport),
+});
diff --git a/packages/eslint-config-ascribe/package.json b/packages/eslint-config-ascribe/package.json
new file mode 100644
index 0000000000..6f3b88ace5
--- /dev/null
+++ b/packages/eslint-config-ascribe/package.json
@@ -0,0 +1,39 @@
+{
+ "name": "eslint-config-ascribe",
+ "version": "3.0.5",
+ "description": "Ascribe's ESLint config, following our styleguide",
+ "main": "index.js",
+ "scripts": {},
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/ascribe/javascript"
+ },
+ "keywords": [
+ "eslint",
+ "eslintconfig",
+ "config",
+ "ascribe",
+ "airbnb",
+ "javascript",
+ "styleguide"
+ ],
+ "author": "Ascribe",
+ "license": "Apache-2.0",
+ "bugs": {
+ "url": "https://github.com/ascribe/javascript/issues"
+ },
+ "homepage": "https://github.com/ascribe/javascript",
+ "dependencies": {
+ "eslint-config-airbnb-base": "^12.1.0"
+ },
+ "peerDependencies": {
+ "babel-eslint": "^8.0.3",
+ "eslint": "^4.12.1",
+ "eslint-plugin-import": "^2.8.0"
+ },
+ "devDependencies": {
+ "babel-eslint": "^8.0.3",
+ "eslint": "^4.12.1",
+ "eslint-plugin-import": "^2.8.0"
+ }
+}
diff --git a/packages/eslint-config-ascribe/rules/custom.js b/packages/eslint-config-ascribe/rules/custom.js
new file mode 100644
index 0000000000..353a4c303f
--- /dev/null
+++ b/packages/eslint-config-ascribe/rules/custom.js
@@ -0,0 +1,148 @@
+// Export ES6 rule overrides against default Airbnb's
+module.exports = {
+
+ /**
+ * Possible Errors
+ * http://eslint.org/docs/rus/#possible-errors
+ */
+
+ // Allow dangling commas for multiline arrays and objects
+ // http://eslint.org/docs/rules/comma-dangle
+ 'comma-dangle': [1, 'only-multiline'],
+
+ // Warn against use of console for non-error logging
+ // http://eslint.org/docs/rules/no-console
+ 'no-console': [1, { 'allow': ['error'] }],
+
+ // Allow use of Object.prototypes builtins directly
+ // http://eslint.org/docs/rules/no-prototype-builtins
+ 'no-prototype-builtins': [0],
+
+
+ /**
+ * Best Practices
+ * http://eslint.org/docs/rules/#best-practices
+ */
+
+ // Allow else clauses after an if with a return
+ // http://eslint.org/docs/rules/no-else-return
+ 'no-else-return': [0],
+
+ // Disallow reassignment of function parameters (but allow assigning to parameter's properties)
+ // http://eslint.org/docs/rules/no-param-reassign.html
+ 'no-param-reassign': [2, { props: false }],
+
+
+ /**
+ * Variables
+ * http://eslint.org/docs/rules/#variables
+ */
+
+ // Disallow use of variables and classes before they are defined
+ // http://eslint.org/docs/rules/no-use-before-define
+ 'no-use-before-define': [2, { "functions": false, "classes": true }],
+
+ // Disallow declaration of variables that are not used in the code, unless they are prefixed by
+ // `ignored` (useful for creating subset objects through destructuring and rest objects)
+ // http://eslint.org/docs/rules/no-unused-vars
+ 'no-unused-vars': [2, {
+ 'vars': 'local',
+ 'args': 'after-used',
+ 'varsIgnorePattern': 'ignored.+'
+ }],
+
+
+ /**
+ * Stylelistic Issues
+ * (http://eslint.org/docs/rules/#stylistic-issues)
+ */
+
+ // Enforce 4-space indents, except for switch cases
+ // http://eslint.org/docs/rules/indent
+ 'indent': [2, 4, { "SwitchCase": 1, "VariableDeclarator": 1 }],
+
+ // Specify the maximum length of a code line to be 100
+ // http://eslint.org/docs/rules/max-len
+ 'max-len': [2, {
+ 'code': 105, // Use 105 to give some leeway for *just* slightly longer lines when convienient
+ 'ignorePattern': '^(import|export) .* from .*$',
+ 'ignoreComments': false,
+ 'ignoreTrailingComments': true,
+ 'ignoreUrls': true
+ }],
+
+ // Require capitalization when using `new`, but don't require capitalized functions to be called
+ // with new
+ // http://eslint.org/docs/rules/new-cap
+ 'new-cap': [2, { 'newIsCap': true, 'capIsNew': false }],
+
+ // Allow the continue statement
+ // http://eslint.org/docs/rules/no-continue
+ 'no-continue': [0],
+
+ // Disallow un-paren'd mixes of different operators if they're not of the same precendence
+ // http://eslint.org/docs/rules/no-mixed-operators
+ 'no-mixed-operators': [2, {
+ groups: [
+ ['+', '-', '*', '/', '%', '**'],
+ ['&', '|', '^', '~', '<<', '>>', '>>>'],
+ ['==', '!=', '===', '!==', '>', '>=', '<', '<='],
+ ['&&', '||'],
+ ['in', 'instanceof']
+ ],
+ allowSamePrecedence: true
+ }],
+
+ // Allow use of unary increment/decrement operators
+ // http://eslint.org/docs/rules/no-plusplus
+ 'no-plusplus': [0],
+
+ // Always allow dangling underscores
+ // http://eslint.org/docs/rules/no-underscore-dangle
+ 'no-underscore-dangle': [0],
+
+ // Require unix-style line breaks
+ // http://eslint.org/docs/rules/linebreak-style
+ 'linebreak-style': [2, 'unix'],
+
+ // Require operators to always be at the end of a line, except for the ternary operator
+ // http://eslint.org/docs/rules/operator-linebreak
+ 'operator-linebreak': [2, 'after', { 'overrides': { '?': 'ignore', ':': 'ignore' } }],
+
+ // Require properties to be consistently quoted. Force numbers to be quoted, as they can have
+ // weird behaviour during the coercion into a string)
+ // http://eslint.org/docs/rules/quote-props
+ 'quote-props': [2, 'consistent', { 'keywords': false, 'unnecessary': true, 'numbers': true }],
+
+ // Require spaces before parens for anonymous function declarations
+ // http://eslint.org/docs/rules/space-before-function-paren
+ 'space-before-function-paren': [2, { 'anonymous': 'always', 'named': 'never' }],
+
+ // Require a space immediately following the // or /* in a comment for most comments
+ // http://eslint.org/docs/rules/spaced-comment
+ 'spaced-comment': [2, 'always', {
+ 'line': {
+ 'exceptions': ['-', '+']
+ },
+ 'block': {
+ 'exceptions': ['*']
+ }
+ }],
+
+ // We don't like semicolons so kill them
+ // http://eslint.org/docs/rules/semi
+ 'semi': [2, 'never'],
+
+
+ /**
+ * ES6-specific Issues
+ * (http://eslint.org/docs/rules/#ecmascript-6)
+ */
+ // Don't require parens in arrow function arguments
+ // http://eslint.org/docs/rules/arrow-parens
+ 'arrow-parens': [0],
+
+ // Ignore built-in import sorting for eslint-plugin-import's version
+ // http://eslint.org/docs/rules/sort-imports
+ 'sort-imports': [0],
+};
diff --git a/packages/eslint-config-ascribe/rules/custom_import.js b/packages/eslint-config-ascribe/rules/custom_import.js
new file mode 100644
index 0000000000..301ccca066
--- /dev/null
+++ b/packages/eslint-config-ascribe/rules/custom_import.js
@@ -0,0 +1,31 @@
+// Export import plugin overrides against default Airbnb's
+module.exports = {
+
+ /**
+ * Import rules
+ * https://github.com/benmosher/eslint-plugin-import#rules
+ */
+
+ // Ensure named imports coupled with named exports
+ // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/named.md#when-not-to-use-it
+ 'import/named': 2,
+
+ // Ensure default import coupled with default export
+ // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/default.md#when-not-to-use-it
+ 'import/default': 2,
+
+ // Disallow namespace (wildcard) imports
+ // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-namespace.md
+ 'import/no-namespace': 2,
+
+ // Enforce imports to not specify a trailing .js extension
+ // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/extensions.md
+ 'import/extensions': [2, { 'js': 'never' }],
+
+ // Enforce module import order: builtin -> external -> internal
+ // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/order.md
+ 'import/order': [2, {
+ 'groups': ['builtin', 'external', ['internal', 'parent', 'sibling', 'index']]
+ }],
+
+};
diff --git a/packages/eslint-config-ascribe/rules/no-es6.js b/packages/eslint-config-ascribe/rules/no-es6.js
new file mode 100644
index 0000000000..afb54cd261
--- /dev/null
+++ b/packages/eslint-config-ascribe/rules/no-es6.js
@@ -0,0 +1,32 @@
+// Export rule overrides to disable all ES6-specific rules
+module.exports = {
+ 'arrow-body-style': [0],
+ 'arrow-parens': [0],
+ 'arrow-spacing': [0],
+ 'constructor-super': [0],
+ 'generator-star-spacing': [0],
+ 'no-class-assign': [0],
+ 'no-confusing-arrow': [0],
+ 'no-const-assign': [0],
+ 'no-dupe-class-members': [0],
+ 'no-duplicate-imports': [0],
+ 'no-new-symbol': [0],
+ 'no-restricted-imports': [0],
+ 'no-this-before-super': [0],
+ 'no-useless-computed-key': [0],
+ 'no-useless-constructor': [0],
+ 'no-useless-rename': [0],
+ 'no-var': [0],
+ 'object-shorthand': [0],
+ 'prefer-arrow-callback': [0],
+ 'prefer-const': [0],
+ 'prefer-reflect': [0],
+ 'prefer-rest-params': [0],
+ 'prefer-spread': [0],
+ 'prefer-template': [0],
+ 'require-yield': [0],
+ 'rest-spread-spacing': [0],
+ 'sort-imports': [0],
+ 'template-curly-spacing': [0],
+ 'yield-star-spacing': [0]
+};
diff --git a/packages/eslint-config-ascribe/settings/custom_import.js b/packages/eslint-config-ascribe/settings/custom_import.js
new file mode 100644
index 0000000000..7a48154df9
--- /dev/null
+++ b/packages/eslint-config-ascribe/settings/custom_import.js
@@ -0,0 +1,4 @@
+module.exports = {
+ // Ignore dependencies, styles sheets, and assets
+ 'import/ignore': ['node_modules', '\.(scss|css)$', '\.(jpe?g|png|gif|svg)'],
+}
diff --git a/react/README.md b/react/README.md
index dd5592f4ed..cb3bdb8707 100644
--- a/react/README.md
+++ b/react/README.md
@@ -1,4 +1,4 @@
-# Airbnb React/JSX Style Guide
+# ~~Airbnb~~ ascribe React/JSX Style Guide
*A mostly reasonable approach to React and JSX*
@@ -13,46 +13,47 @@
1. [Props](#props)
1. [Parentheses](#parentheses)
1. [Tags](#tags)
- 1. [Methods](#methods)
1. [Ordering](#ordering)
## Basic Rules
- - Only include one React component per file.
+ - Only `default export` one React component per file.
- Always use JSX syntax.
- - Do not use `React.createElement` unless you're initializing the app from a file that is not JSX.
+ - Use `React.createElement` instead of `class extends React.Component`
+ - Prefer stateless components over stateful components
+ - Don't use mixins
## Class vs React.createClass
- - Use class extends React.Component unless you have a very good reason to use mixins.
+ - Use `React.createClass`; don't use the ES6 class syntax for now
```javascript
// bad
- const Listing = React.createClass({
- render() {
- return ;
- }
- });
-
- // good
class Listing extends React.Component {
- render() {
- return ;
- }
+ render() {
+ return ;
+ }
}
+
+ // good
+ const Listing = React.createClass({
+ render() {
+ return ;
+ }
+ });
```
## Naming
- - **Extensions**: Use `.jsx` extension for React components.
- - **Filename**: Use PascalCase for filenames. E.g., `ReservationCard.jsx`.
+ - **Extensions**: Use `.js` extension for React components.
+ - **Filename**: Use snake_case for filenames. E.g., `reservation_card.js`.
- **Reference Naming**: Use PascalCase for React components and camelCase for their instances:
```javascript
// bad
- const reservationCard = require('./ReservationCard');
+ const reservationCard = require('./reservation_card');
// good
- const ReservationCard = require('./ReservationCard');
+ const ReservationCard = require('./reservation_card');
// bad
const ReservationItem = ;
@@ -61,32 +62,59 @@
const reservationItem = ;
```
- **Component Naming**: Use the filename as the component name. For example, `ReservationCard.jsx` should have a reference name of `ReservationCard`. However, for root components of a directory, use `index.jsx` as the filename and use the directory name as the component name:
+ **Component Naming**: Convert snake_case filename to PascalCase component name. For example, `reservation_card.js` should have a reference name of `ReservationCard`.
+ ```javascript
+ // bad
+ const Footer = require('./footer_component.js');
+
+ // good
+ const FooterComponent = require('./footer_component.js');
+ ```
+
+ However, for root components of a directory, use `index.js` as the filename and use the directory name as the component name:
```javascript
// bad
- const Footer = require('./Footer/Footer.jsx')
+ const Footer = require('./footer/footer.js');
// bad
- const Footer = require('./Footer/index.jsx')
+ const FooterDir = require('./footer/index.js');
// good
- const Footer = require('./Footer')
+ const Footer = require('./footer/index.js');
+
+ // better
+ const Footer = require('./footer');
+ ```
+
+ **Note**: We typically allow our module loaders to resolve `.js` files without specifying the extension, so imports without the extension will also work (and are preferred):
+ ```javascript
+ const Footer = require('./footer'); // actual file is footer.js
+ const Footer = require('./footer/index'); // actual file is index.js
```
## Declaration
- - Do not use displayName for naming components. Instead, name the component by reference.
+ - Declare displayName for higher level components. Otherwise just name the component by reference.
```javascript
// bad
- export default React.createClass({
- displayName: 'ReservationCard',
- // stuff goes here
+ const ReservationCard = React.createClass({
+ displayName: 'ReservationCard',
+ // stuff goes here
});
// good
- export default class ReservationCard extends React.Component {
+ function ReservationCard() {
+ return React.createClass({
+ displayName: 'ReservationCard',
+ // stuff goes here
+ });
}
+
+ // good
+ const ReservationCard = React.createClass({
+ // stuff goes here
+ });
```
## Alignment
@@ -94,24 +122,25 @@
```javascript
// bad
-
+
// good
+ superLongParam="bar"
+ anotherSuperLongParam="baz" />
+
// if props fit in one line then keep it on the same line
// children get indented normally
-
+ superLongParam="bar"
+ anotherSuperLongParam="baz">
+
```
@@ -157,15 +186,28 @@
```javascript
// bad
+ phone_number={12345678}
+ UserName="hello" />
// good
+ phoneNumber={12345678}
+ userName="hello" />
+ ```
+
+ - Always specify the props in alphabetical order, and put shorthand boolean props before props whose values are explicitly declared
+ ```javascript
+ // bad
+
+
+ // good
+
-
- ;
+ return
+
+ ;
}
// good
render() {
- return (
-
-
-
- );
+ return (
+
+
+
+ );
}
// good, when single line
render() {
- const body = hello
;
- return {body};
+ const body = hello
;
+ return {body};
}
```
@@ -204,48 +246,20 @@
```
- - If your component has multi-line properties, close its tag on a new line.
- ```javascript
- // bad
-
-
- // good
-
- ```
-
-## Methods
- - Do not use underscore prefix for internal methods of a React component.
- ```javascript
- // bad
- React.createClass({
- _onClickSubmit() {
- // do stuff
- }
-
- // other stuff
- });
-
- // good
- class extends React.Component {
- onClickSubmit() {
- // do stuff
- }
-
- // other stuff
- });
- ```
-
## Ordering
- - Ordering for class extends React.Component:
-
- 1. constructor
- 1. optional static methods
+#### `React.createClass`:
+
+ 1. displayName
+ 1. propTypes, ordered by these rules:
+ * Alphabetical order
+ * Required props before optional ones
+ * Injected props (ie. props implicitly passed down by a parent that should not be explicitly declared in jsx) should be last, preferrably with a comment
+ 1. contextTypes
+ 1. childContextTypes
+ 1. mixins
+ 1. getDefaultProps
+ 1. getInitialState
1. getChildContext
1. componentWillMount
1. componentDidMount
@@ -254,62 +268,73 @@
1. componentWillUpdate
1. componentDidUpdate
1. componentWillUnmount
+ 1. *exposed imperative API* (should be avoided, but sometimes you'll have no other choice but to provide an imperative API)
+ 1. *private helper methods*
1. *clickHandlers or eventHandlers* like onClickSubmit() or onChangeDescription()
1. *getter methods for render* like getSelectReason() or getFooterContent()
1. *Optional render methods* like renderNavigation() or renderProfilePicture()
1. render
- - How to define propTypes, defaultProps, contextTypes, etc...
+ - Example:
+
+ ```javascript
+ import React from 'react';
+
+
+ const Link = React.createClass({
+ propTypes: {
+ id: PropTypes.number.isRequired,
+ url: PropTypes.string.isRequired,
+ text: PropTypes.string
+ },
+
+ getDefaultProps() {
+ return {
+ text: 'Hello World'
+ };
+ },
+
+ render() {
+ const { id, text, url } = this.props;
+
+ return {text};
+ }
+ });
+ ```
+
+#### Stateless components:
+
+ 1. propTypes declaration, as a `const` variable. See `React.createClass` ordering rules for propTypes ordering.
+ 1. contextTypes declaration, as a `const` variable
+ 1. defaultProps declaration, as a `const` variable
+ 1. Component declaration
+ 1. displayName attachment to component
+ 1. propTypes attachment to component
+ 1. contextTypes attachment to component
+ 1. defaultProps attachment to component
+
+ - Example:
```javascript
- import React, { Component, PropTypes } from 'react';
-
+ import React from 'react';
+
+
const propTypes = {
- id: PropTypes.number.isRequired,
- url: PropTypes.string.isRequired,
- text: PropTypes.string,
+ id: PropTypes.number.isRequired,
+ url: PropTypes.string.isRequired,
+ text: PropTypes.string
};
-
+
const defaultProps = {
- text: 'Hello World',
+ text: 'Hello World'
};
-
- export default class Link extends Component {
- static methodsAreOk() {
- return true;
- }
-
- render() {
- return {this.props.text}
- }
- }
-
+
+ const Link = ({ id, text, url }) => (
+ {text}
+ );
+
+ Link.displayName = 'Link';
Link.propTypes = propTypes;
Link.defaultProps = defaultProps;
```
-
- - Ordering for React.createClass:
-
- 1. displayName
- 1. propTypes
- 1. contextTypes
- 1. childContextTypes
- 1. mixins
- 1. statics
- 1. defaultProps
- 1. getDefaultProps
- 1. getInitialState
- 1. getChildContext
- 1. componentWillMount
- 1. componentDidMount
- 1. componentWillReceiveProps
- 1. shouldComponentUpdate
- 1. componentWillUpdate
- 1. componentDidUpdate
- 1. componentWillUnmount
- 1. *clickHandlers or eventHandlers* like onClickSubmit() or onChangeDescription()
- 1. *getter methods for render* like getSelectReason() or getFooterContent()
- 1. *Optional render methods* like renderNavigation() or renderProfilePicture()
- 1. render
-
-**[⬆ back to top](#table-of-contents)**
+#