javascriptnode.jsrequirejseval

How do I name an imported module dynamically with javascript eval()?


I want to create a dynamically named variable so that I can use it as a module. I am using eval() to do it, but for some reason it's not working as expected and claiming that the constant I created inside of it doesn't exist.

I have a main folder with this structure:

main
|- commands
|- |- testmod.js
|- test.js

Testmod.js has a simple function export inside of it that logs something to console when run:

function cmd() {
    console.log('it worked :)');
}

module.exports = { cmd };

And in test.js, I want to try importing it dynamically:

const foo = 'testmodule';
eval(`const ${foo} = require('./commands/testmod.js');`);

eval(`${foo}.cmd();`)

However, it runs with an error, ReferenceError: testmodule is not defined, and I don't know why. Expected:

1. define a variable named foo
2. evaluate a string that requires contents of another js file, and name that import as the contents of variable foo
3. evaluate this: a module with name of variable foo and then run the command 'cmd()' inside of it.

expected output: it worked :)

Should I try to find a different method of dynamically naming variables? I'm 99% sure that this method of doing things is unstable and unintended, but if I could get it to work somehow it would be great.


Solution

  • Alright, so my solution was to create an Object, then assign stuff to it. This way, there aren't any new variables and its just an object that can be called later. Thanks Emiel.

    const foo = 'testmodule';
    let bar = {
        foo: require('./commands/testmod.js'),
    };
    
    bar.foo.cmd();