YPCrumble YPCrumble - 1 month ago 6
Node.js Question

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');

Answer

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.

Comments