Is it possible to import variables in JavaScript (node.js)?

I could assign a local variables for every property export&required module G object, but obviously it’s a tedious process to add every variable to the test file manually to correspond the G objects.

No, that’s how it is supposed to work. You – and only you – are in charge of what local variables exist in your module scope. No changes in the “export variables” of an included module should break your code.

Accessing properties on the imported module (with a self-chosen name) is the way to go. This is quite equivalent to Python’s import app or import app as g.

If you want some particular properties as local variables, you will usually choose them manually, as in Python’s from app import DATA, F1. In JS, you will need a multiple var statement like the one you’ve shown in your question. However, there is a syntax feature called destructuring assignment which will make this more fluid. You can use this in JavaScript 1.7+ (Gecko), CoffeeScript, or EcmaScript 6:

var {DATA, F1} = require("app.js");

Is there any way to do this automatically?

Yes and No. You should not do this, but you can – just like Python’s frowned-upon from app import *. To cite what they say, which is equally true for JavaScript:

[It] introduces an unknown set of names into the interpreter, possibly
hiding some things you have already defined.

Note that in general the practice of importing * from a module or
package is frowned upon, since it often causes poorly readable code.
However, it is okay to use it to save typing in interactive sessions.

In JavaScript, you can[1] use the with-statement:

with (require("app.js")) {
    …
}

[1]: Not in ES5.1 strict mode, though – which is recommended for optimisation

Leave a Comment