Search code examples
javascriptnode.jsrequire

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.


Solution

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