我希望我的程序从我的服务器下载一个javascript文件,然后运行该文件中包含的代码。下载部分很好,但我无法弄清楚如何从文件中运行代码。
我能想到的最明显的答案(不起作用)将使用import:
//download the file and save it in the current directory as codeFile.js
downloadCodeFile();
import codeFile from './codeFile.js;
//call it
codeFile();
但是web pack不允许动态导入,因此不起作用。
我可以读取文件的内容:
import fs from 'fs'
downloadCodeFile();
const codeFileContents = fs.readFileSync('./codeFile.js).toString();
然后我有一个包含所有代码的字符串,但我不知道如何让它从那一点实际运行。
我认为使用eval有一个潜在的解决方案(虽然我不确定如何实现它),但我基本上被告知永远不要使用eval所以我想知道是否有一个更好的解决方案,我缺少
如果eval是一个好的解决方案,我将如何做到这一点?如果有更好的方法,会是什么?
答案 0 :(得分:0)
Webpack 2
允许您动态导入模块。例如,您可以使用下一个代码:
import('path/to/your/module')
.then(module => /* use your module here */)
import()
返回一个使用所需模块解析的promise。
Webpack也支持require.ensure
。