从字符串变量导入模块

从字符串变量导入模块

本文介绍了从字符串变量导入模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从内存变量中导入一个 JavaScript 模块.我知道这可以使用 SystemJSWebpack 来完成.

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

但是我在任何地方都找不到好的工作示例或文档.文档主要讨论 .js 文件的动态导入.

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

推荐答案

import 语法存在一些限制,如果不使用外部库,就很难完成.

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

我能得到的最接近的是使用 Dynamic Import 语法.一个例子如下:

The closest I could get is by using the Dynamic Import syntax. An example follows:

<!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>

然而,您会注意到这对构建导入代码的方式有一些限制,可能与您的需要不完全匹配.最简单的解决方案可能是将模块的代码发送到服务器上,让它生成一个临时脚本,然后使用更传统的语法导入.

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.

这篇关于从字符串变量导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:32