«

Setting rule options in yaml eslintrc files

I’ve forgotten this once already, so it’s time for a blog post so I can find the information via Google next time I need it.

Tools that enforce coding styles are always important, but doubly so when working with languages that are untyped and not compiled. In a language like JavaScript an automated linting tool that enforces best practices and identifies likely coding mistakes is a must have.

Eslint is my linting tool of choice for JavaScript. Part of it’s power is it’s configurability. You can enable or disable rules as they make sense for your coding style. Some rules expose options to further customize how they are enforced.

For example, the rule no-param-reassign prevents a common issue where someone naively believes that reassigning a function parameter inside that function will also reassign the variable which was passed by the caller. This is not the case, since parameters are passed by value and not by reference.

Here’s a quick example:

// this function naively tries to
// reassign thing. it won't work.
function reassignTheThing(thing) {
  thing = {
    x: 8,
    y: 6
  };

  // inside reassignTheThing, the "thing" has been
  // re-assigned
  console.log('thing in reassignTheThing:', thing);
}

function makeSomething(name) {
  const p = {
    name
  };

  reassignTheThing(p);

  // however, "p" hasn't changed in this
  // scope, because it was passed by value
  // to changeTheThing
  console.log('p in makeSomething:', p);

  return p;
}

const something = makeSomething('nancy');
console.log('something in global scope:', something);

The style guide I use, airbnb’s base style, enforces the no-param-reassign rule which is good. Unfortunately, it enables the props option for that rule. That option prevents you from writing code like:

function modifySomething(thing) {
  thing.superCoolProperty = 'some value';
}

I consider functions that modify an object pretty useful in a lot of circumstances.

No problem, I just have to override that property. Unfortunately, I haven’t found an example of the exact syntax to use to set rule properties in .eslintrc files created with yaml syntax. Most of the examples in the Eslint documentation are in json format. So, here’s what I got working after some trial and error:

extends: airbnb-base
env:
  node: true
  es6: true
rules:
  no-param-reassign:
    - 2
    - props: false

The syntax is pretty obvious once you see it, but I’m not very familiar with yaml and I’ve had trouble remembering it as I mentioned earlier.