Tools & best practices for writing JavaScript across Conveyal projects.
Completely necessary for modern JavaScript development. Install with a package manager. YOU MUST use a 6.x.x
version for Conveyal development.
$ brew install node@10
Use yarn
as an npm
replacement to manage dependencies.
$ brew install yarn
Use n
to manage Node.js versions.
$ yarn global add n
$ n latest
Certain conventions should be followed due to the new functionality that ES6 brings. Highlights:
- When working on a new codebase, use
let
for variables that will change their value over time, andconst
for variables which cannot be reassigned. - Use Arrow Functions (
=>
) in place of function expressions when possible. - Use
Promise
s instead of thefunction asyncFunc (input, function callback (err, result) {}) {}
style.
Use Promises
, async
/await
and watch out for callback hell
Promiseified functions can be awaited
allowing for this style of functions:
async function chainAnimationsAsync(elem, animations) {
let ret = null
try {
for(const anim of animations) {
ret = await anim(elem)
}
} catch (e) {
/* report and keep going */
}
return ret
}
Always use debug
instead of console.log
Debug is a tiny library that allows you to selectively turn on and off namespaced log statements in the browser and in node.
import dbg from 'debug'
const debug = dbg('library:module')
debug('log this!')
The log will only be shown in the browser when you turn it on via simple regexp in the console:
> localStorage.setItem('debug', 'library*')
Do:
onClick={(e) => this.handleEvent(e)}
Don't
onClick={this.handleEvent.bind(this)}
In classes you can auto-bind to the instance by using class properties and arrow functions.
class Foo {
handleEvent = (e) => {
// inside this function `this` will always be the instance of `Foo`
}
}
To start, see: http://youmightnotneedjquery.com/. Use ES6 and smaller modern JavaScript libraries instead of using jQuery.
Use fetch
instead of $.ajax
/$.get
/$.post
:
fetch(url)
.then(res => res.json())
.then(data => {
console.log(data)
})