BLOG

JS Static Analysis Part 1 - VS Code with JSDoc

This is Part 1 of a 4 part intro series to static analysis tooling for JavaScript:

The first and easiest step to help writing better JavaScript is using Visual Studio Code and setting up a jsconfig.json file.

By default, if you start writing a new project in JavaScript, the lightbulb in the bottom right corner will prompt you to create a new jsconfig.json file. By default VS Code will create this file for you if you allow it to:

jsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "allowSyntheticDefaultImports": true
  },
  "exclude": [
    "node_modules",
    "bower_components",
    "jspm_packages",
    "tmp",
    "temp"
  ]
}

With this in place you can use JSDoc style annotations to get some nice Intellisense options.

a.js

var b = require('./b');
var sum = b.addTwo(5, 2);

b.js

/**
 * @param {number} first - The first number
 * @param {number} second - The second number
 * @returns {number} - Returns the sum of two numbers
 */
function addTwo(first, second) {
  return first + second;
}

module.exports = {
  addTwo: addTwo
};

This allows us to get some nice features. First when you hit the period you get:

JSDoc 1

And as you select the function, you get:

JSDoc 2

What about something from node_modules? Let’s install lodash.

> npm init -y
> npm install lodash --save

Still nothing at this point. We need to install a TypeScript typings file first. Even though our application doesn’t use TypeScript, we can still use the built-in functionality from VS Code to assist us.

> npm install -g typings
> typings install lodash --save

Cool, now we get Intellisense on all of our lodash functions:

Typings 1

calendartwitterfeedenvelopelinkedingithub-altbitbucket