Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EsLint - Suppress "Do not use 'new' for side effects"

Tags:

eslint

Here's the documentation for the ESLint rule in question: http://eslint.org/docs/rules/no-new.html

Disallow new For Side Effects (no-new)

The goal of using new with a constructor is typically to create an object of a particular type and store that object in a variable, such as:

var person = new Person();

It's less common to use new and not store the result, such as:

new Person();

In this case, the created object is thrown away because its reference isn't stored anywhere, and in many cases, this means that the constructor should be replaced with a function that doesn't require new to be used.

I pasted that above because I think it's important to understand what the intent of the rule is, and not just how to make it go away.

If you can't find a way to get rid of new, you can suppress this error with the eslint-disable directive:

fetchJsAnimation() {
  /* eslint-disable no-new */
  const animation = this.refs.Animation;
  new AnimateSlideShow(animation);
}

ESLint directives are block-scoped, so it will be suppressed inside this function only. You can also suppress rules on a single line with the eslint-disable-line directive:

new AnimateSlideShow(animation); // eslint-disable-line no-new

If you really need to disable this rule for your entire project, then in your .eslintrc's "rules" section set the value for this rule to 0:

{
  // ...
  "rules": {
    "no-new": 0,
    // ...
  }
}

You can also make it a warning instead of an error by setting it to 1 (2 is error).


Try to cover your function into an anonim function

(()=>code)();

in your example

fetchJsAnimation() {
  const animation = this.refs.Animation;
  (()=>new AnimateSlideShow(animation))();
}

Or you can use this pattern for example modern javascript framework eg. vuejs vue Here is an example

(() => new Vue({ 
    el: '#app', 
    router, 
    store, 
    components: { App }, 
    template: '<App/>' 
}))();

Extending on sarkiroka answer, here's an ES5 version (essentially an IIFE with a return statement):

(function (Vue) {
  'use strict';

  return new Vue({
    el: '.unity-header-wrapper'
  });
}(Vue));

We're avoiding ESLint unused var error, which appears if used this way:

var myApp = new Vue({
  el: '.unity-header-wrapper'
});

We're also avoiding using standalone 'new Vue()' instantiation (which prevents side effects error on ESLint)

var myApp = new Vue({
  el: '.unity-header-wrapper'
});

You can also add Vue as a global in ESLint config, to avoid undefined global var error, as seen here: Global variables in Javascript and ESLint

// .eslintrc.json
"globals": {
  "Vue": true
}