Zaz
Zaz

Reputation: 48769

How do you require variables without a prefix

I have a file with some helper functions to be used in two other files. I want to import the functions, but the way I'm used to doing this is not ideal:

helper = require('./helpers')
helper.log()
helper.ok()
...

I'd like to be able to use the functions without the helper prefix (e.g. ok()). How can I do this?

Edit: There are currently 7 helper functions, and that number may grow in the future, so specifying each function by hand seems like it defeats the purpose of using a separate file.

Upvotes: 0

Views: 1143

Answers (4)

nisetama
nisetama

Reputation: 8863

You can also use node -r ./myfunctions.js (where the argument has to be an absolute path or to start with ./), or you can run .load myfunctions.js in the REPL:

$ cat myfunctions.js
p=console.log
$ node -r ./myfunctions.js
Welcome to Node.js v18.3.0.
Type ".help" for more information.
> p(5)
5
undefined
>
$ node
Welcome to Node.js v18.3.0.
Type ".help" for more information.
> .load myfunctions.js
p=console.log

[Function: log]
> p(5)
5
undefined
$ alias node='node -r ~/myfunctions.js'
$ echo 'p(5)'>script.js
$ node script.js
5

Upvotes: 0

mauris
mauris

Reputation: 43619

Unlike ES2015, Python or other languages, you cannot export a specific function from another file and use it directly. What you can do in ES5 is to:

helper = require('./helpers')
var ok = helper.ok;

ok(...);
...

Or if you prefer oneliners:

var ok = require('./helpers').ok

That is I presume you are exporting a single object of the various functions you have in helpers.js.

Whereas in ES2015, you have to write it slightly differently.

First, your helpers.js needs to export the functions separately like this:

export function ok(args) {
  ...
}

export function log(args) {
  ...
}

Then in your main script:

import {ok, log} from './helpers';
ok(...);
log(...);

See more: https://developer.mozilla.org/en/docs/web/javascript/reference/statements/import

Upvotes: 6

Zaz
Zaz

Reputation: 48769

Seeing as nobody has yet offered a solution that doesn't involve specifying each function you want to import, here's a solution that is perhaps not ideal, but works:

const helpers = require("./lib")
for (let k in helpers) {
    eval(`var ${k} = helpers.${k}`)
}

Upvotes: -4

str
str

Reputation: 44979

You could use object destructuring:

const {log, ok} = require('./helpers');
log();
ok();

Upvotes: 7

Related Questions