user4893295
user4893295

Reputation: 651

Correct way to require modules to prevent eslint erroring

I've recently started using eslint, and I'm finding that all my code is erroring where I have required modules, as it says that the function names aren't assigned.

mymodule.js

module.exports = {
  one: function() {
    console.log(1);
  },
  two: function() {
    console.log(2);
  }
}

index.js

require('./mymodule.js');
one(); // eslint says 'one is not defined'

Should I be declaring 'one' as a variable beforehand, is that the correct way of doing it? Or is there a better way?

Upvotes: 0

Views: 106

Answers (2)

GOTO 0
GOTO 0

Reputation: 47682

What I usually do is adding a global comment at the top of the file:

/* global one */

require('./mymodule.js');
one();

You can also specify more identifiers as a comma-separated list: /* global one, two */.

Alternatively, you can add your undeclared identifiers to the global section of your .eslintrc file:

{
    ...

    "globals": {
        "one": "readonly"
    },

    ...
}

More info: https://eslint.org/docs/user-guide/configuring#specifying-globals

Upvotes: 1

nahanil
nahanil

Reputation: 522

I can't run your example "index.js" at all (Node 8.15) as the node interpreter itself tells me the same thing eslint is telling you ReferenceError: one is not defined. Stuff you export/import from a module doesn't magick itself into the global namespace.

I'd do either of the following:

A) Import the whole of mymodule

const mymodule = require('./mymodule');
mymodule.one();

B) Import the fun parts of mymodule by name

const { one /* , two, three, etc */ } = require('./mymodule');
one();

C) Import a single member of mymodule

const one = require('./mymodule').one;
one();

Upvotes: 0

Related Questions