Is there a way to execute a JavaScript string as some functions? I'm using eval but it isn't working.
I'm trying this as I need to read values from a YML file for my serenity js test.
This is what I'm trying to do
this.data = "element1.element2"
this.test1 = "safeLoad(readFileSync(`config/${this.fileName}.yml`, 'utf8'))";
console.log(this.test1)
console.log(`${this.test1}.${this.data}`);
And this is how I'm trying to execute the string
eval(`${this.testabc}.${this.data}`)
However, when I execute this, I'm having the following error:
ReferenceError: safeLoad is not defined
P.S.: If I execute the code normally (without eval) it works fine!
safeLoad(readFileSync(`config/${this.fileName}.yml`, 'utf8')).element1.element2
Does anyone know how to execute code like that as a string?
I guess you
import safeLoadusing es6 syntax.If yes, when you use
babelto transpile code,safeLoadwill be omitted. Because the transpiler though that safeLoad will not be used on your code.To understand, please check the bellowing picture, or this babel example.
To fix this, you should use
requireinstead ofimport(es6):