I will like my vue application to transform the following string:
const test = 'import { pi } from "MathPie"; function test() { console.log(pi); } export default test;'
into a function that I could call.
import { pi } from "MathPie";
function test() {
console.log(pi);
}
export default test;
I already tried using eval (even if it's evil), but it doens't work because import statement aren't supported by it.
eval(test)()
> Cannot use import statement outside a module
> Should log '3.14159'
The snippet is for presentation only, I'm aware of Math.PI
My question is how I can evaluate a string with import statement?
In your case, you can use a combination of dynamic import() together with createObjectURL().
A test example is below:
(async() => { // <= if you don't support top level await.
const jsCode = `
export default function defaultTest() { console.log('this is default test func'); };
export function primaryTest() { console.log('this is primary test func'); };
export function secondaryTest() { console.log('this is secondary test func'); };`;
const blobData = new Blob([jsCode], {
type: 'text/javascript'
});
const url = URL.createObjectURL(blobData);
const {
"default": defaultTest,
primaryTest,
secondaryTest
} = await import(url);
defaultTest();
primaryTest();
secondaryTest();
})()