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
PS: 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 safeLoad
using es6 syntax.
If yes, when you use babel
to transpile code, safeLoad
will 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 require
instead of import(es6)
:
// instead of
import safeLoad from 'safeLoad'
// use this:
const safeLoad = require('safeLoad').default
// instead of
import { safeLoad } from 'safeLoad'
// use this:
const { safeLoad } = require('safeLoad')
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.