13

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');
1
  • Looks like you only assigned it to the third variable. Why not use an object instead? Commented Jan 8, 2016 at 18:12

3 Answers 3

21

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Maybe worth noting that destructuring isn't supported in Node yet (by default).
So what should we do for it to support it?
@samuelnihoul Node 4 is waaay out of date. Any modern version of Node supports destructuring
7

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

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

Comments

2

You could store them in an array:

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

9 Comments

How is that better than an object?
@FelixKling it depends on the problem. "first, second, third" imply homogeneity and since the names don't have any information other than, well, the index, an array may be better.
@djechlin: that doesn't make a big difference regarding the issue though (how to import those values).
@djechlin: The question is how to import multiple values. This answer suggests to use an array instead of an object. I don't see how that answers the question (that's basically what my comment implied).
@djechlin: {first, second, third} is short object notation and is equivalent to {first: first, second: second, third: third}. It is valid code, hence my confusion about the array. The issue is with importing the value, not exporting it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.