0

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.

182exe
  • 66
  • 7
  • 2
    `const` is scoped to the block in which it is defined. That means that the `testmodule` constant is not available outside of the scope of `eval`. However, using `eval` should be avoided if possible. You can dynamically create properties on objects: `const bar[foo] = require('./commands/testmod.js');` [See this related question](/questions/5117127/use-dynamic-variable-names-in-javascript) – Emiel Zuurbier Dec 24 '22 at 22:36
  • @EmielZuurbier Do you have any links to questions that have more explanation on how to do the `bar[foo]` thing? I don't really understand how to implement it. edit: nevermind, I think i've got something working now. [This question makes it more understandable for me.](https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) Thanks :) – 182exe Dec 24 '22 at 23:16

1 Answers1

1

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();
182exe
  • 66
  • 7