tc39 / proposal-dynamic-import

import() proposal for JavaScript

Home Page:https://tc39.github.io/proposal-dynamic-import/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Dynamic import on strings?

shawnmclean opened this issue · comments

This is related to #76, if we are pulling this module via HTTP, this is essentially an HTTP request and evaluating the body as javascript.

What are the alternatives to dynamic import but allow us to evaluate a string as a module, let us handle the HTTP part ourselves?

commented

You can use Blob to load any string or binary as a URL:

async function withBlob(blob, f) {
    const url = URL.createObjectURL(blob);
    try {
        return await f(url);
    } finally {
        URL.revokeObjectURL(url);
    }
}

function withJsString(string, f) {
    return withBlob(new Blob([string], { type: "text/javascript" }), f);
}

You use it like this:

const exports = await withJsString("...", (url) => import(url));

Or if you already have a Blob (from fetch) then you can pass it directly:

const response = await fetch(...);
const blob = await response.blob();
const exports = await withBlob(blob, (url) => import(url));