Code analysis with Tern.js

As mentioned earlier, build-time type checking is helpful for finding errors in your code while you write it as it flags them while you develop. Although this is helpful, it carries with it a fair bit of extra effort and configuration. Meanwhile, the other half of why things such as type definitions are helpful is that they improve the developer experience by providing API documentation and code analysis.

You can get quite a lot of this functionality without using static typing through a piece of tooling called Tern.js. Tern is a code analysis engine that scans your modules and provides feedback to other tooling. You generally don't use it on its own; you install a plugin for your code editor of choice and it talks to Tern.

Atom, Sublime, and other IDEs have plugins -- how you install them is dependent upon your IDE. I personally use Atom with atom-ternjs:

When Tern's all configured in Atom, it provides code completion, such as the preceding. Note how, just by typing d3.se, I've brought up both d3.select and d3.selectAll, plus their function signatures? This is helpful for ensuring that you pass the correct types to various functions. Tern can do more, though--if you have a documentation comment as shown:

/** 
* Isn't documentation splendid?
* @param {string} llama lama
* @param {number} duck anatinae
* @param {array} rest mushroom, brick, potato
* @return {string} A silly value
*/
function testTern(llama, duck, ...rest) {
return 'llama llama duck';
}

It will autocomplete with far more information, like this:

To install Tern globally, run the following:

$ npm install -g tern

You generally need to do this before Tern starts working in your IDE. You also need to create a Tern config file. Add the following to a file called .tern-project in the root of your project directory:

{ 
"ecmaVersion": 7,
"libs": [
"browser"
],
"plugins": {
"doc_comment": {
"fullDocs": true,
"strong": false
},
"node": {
"dontLoad": "",
"load": "",
"modules": ""
},
"modules": {
"dontLoad": "",
"load": "",
"modules": ""
},
"es_modules": {}
}
}

Install a Tern plugin to your IDE of choice and you should start seeing rich code completion provided by Tern.

Unfortunately, D3.js doesn't have anything in terms of internal documentation and so Tern.js is far more useful when you document your own code well. In the next section, we'll use TypeScript, which has an excellent type definition for D3, in essence pulling a lot of documentation into your editor.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset