简体   繁体   中英

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 (eg 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.

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

You could use object destructuring :

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

In the REPL, you can either run node -r./myfunctions.js (it has to be an absolute path or start with ./ ) or run .load myfunctions.js :

~ 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

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}`)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM