Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
28
rated 0 times [  31] [ 3]  / answers: 1 / hits: 18643  / 5 Years ago, sat, july 20, 2019, 12:00:00

I need to import a JavaScript module from an in memory variable.
I know that this can be done using SystemJS and Webpack.



But nowhere can I find a good working example nor documentation for the same. The documentations mostly talks of dynamic import of .js files.



Basically I need to import the module like below



let moduleData = export function doSomething(string) { return string + '-done'; };
//Need code to import that moduleData into memory


If anyone can point to documentation that will be great


More From » angular

 Answers
36

There are limitations in the import syntax that make it difficult to do if not impossible without using external libraries.


The closest I could get is by using the Dynamic Import syntax. Two examples follow: the first one is the original I wrote while the second one is an edit from a user that wanted to modernize it.


The original one:


<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<script>
var moduleData = "export function hello() { alert('hello'); };";
var b64moduleData = "data:text/javascript;base64," + btoa(moduleData);

</script>
<script type="module">

async function doimport() {
const module = await import(b64moduleData);
module.hello();
}

doimport();

</script>

</body>
</html>

The modernized one:


function doimport (str) {
if (globalThis.URL.createObjectURL) {
const blob = new Blob([str], { type: 'text/javascript' })
const url = URL.createObjectURL(blob)
const module = import(url)
URL.revokeObjectURL(url) // GC objectURLs
return module
}

const url = "data:text/javascript;base64," + btoa(moduleData)
return import(url)
}

var moduleData = "export function hello() { console.log('hello') }"
var blob = new Blob(["export function hello() { console.log('world') }"])

doimport(moduleData).then(mod => mod.hello())

// Works with ArrayBuffers, TypedArrays, DataViews, Blob/Files
// and strings too, that If URL.createObjectURL is supported.
doimport(blob).then(mod => mod.hello())

You will however notice that this has some limitations on the way the import code is constructed, which may not precisely match what you need.
The simplest solution is probably to send the code of the module on the server for it to generate a temporary script to be then imported using a more conventional syntax.


[#51856] Sunday, July 14, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
draven

Total Points: 641
Total Questions: 101
Total Answers: 110

Location: Nicaragua
Member since Mon, Sep 26, 2022
2 Years ago
draven questions
Tue, Apr 12, 22, 00:00, 2 Years ago
Thu, Feb 17, 22, 00:00, 2 Years ago
Tue, Nov 30, 21, 00:00, 3 Years ago
Tue, Oct 19, 21, 00:00, 3 Years ago
;