YPCrumble
YPCrumble

Reputation: 28692

How do I import many variables at once in javascript in NodeJS?

Let's say I have a javascript module first_file.js:

var first = "first",
    second = "second",
    third = "third";

module.exports = {first, second, third};

How do I import these into another file in one line? The following only imports third:

var first, second, third = require('./path/to/first_file.js');

Upvotes: 13

Views: 12920

Answers (3)

Mike Cluck
Mike Cluck

Reputation: 32511

You're exporting an object with those properties. You can get them either using the object directly:

var obj = require('./path/to/first_file.js');
obj.first;
obj.second;
obj.third;

Or using destructuring:

var { first, second, third } = require('./path/to/first_file.js');

As of version 4.1.1, Node.js does not yet support destructuring out of the box.

Upvotes: 21

madox2
madox2

Reputation: 51861

In ES6 (ECMAScript 2015) you can use object destructuring:

const { first, second, third } = require('./path/to/first_file.js');

Upvotes: 7

gnerkus
gnerkus

Reputation: 12019

You could store them in an array:

module.exports = [first, second, third];

Upvotes: 2

Related Questions