[Vuejs]-Transform javascript string with `import` statement into a function in the browser

3πŸ‘

βœ…

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();
})()

Leave a comment