在我的网络应用程序中,我想让用户能够编写自己的模块以在应用程序中使用。这些最好在客户端用 JS 编写。
但是,我在允许应用程序访问客户端创建的类时遇到问题。最初我想要某种模块导入,但动态导入仍然需要一个路径,出于安全原因,浏览器无法访问该路径。直接将 JS 导入到脚本标记中会污染全局命名空间,这也不理想。
有什么明智的方法可以做到这一点吗?理想情况下,我希望导入该类,例如
// MyClass.js, on the client side
export default class MyClass {
myPrint() {
console.log('ya blew it');
}
}
然后在 App.js 中:
import(somehow_get_this_path).then((MyClass) => { etc});
这条路可能吗?当前的 namespace 污染方法使用选择文件对话框,但不允许我告诉 import 它具有什么路径。你得到的只是一个 Blob 。我对这个东西还很陌生,所以如果这个问题很愚蠢,我深表歉意。
编辑:我尝试使用 CreateObjectURL 获取对象 URL,但出现错误:
Error: Cannot find module 'blob:null/d651a896-d568-437f-86d0-72ebcee7bc56'
最佳答案
如果您使用 webpack 作为 bundler ,那么可以使用 magic comments延迟加载组件。
否则您可以使用动态导入。
import('path_to_my_class').then(MyClass => {
// Do something with MyClass
});
编辑1:-
您可以使用此代码获取上传的 js 文件的有效本地 URL。尝试使用这个
const path = (window.URL || window.webkitURL).createObjectURL(file);
console.log('path', path);
已编辑 2:-
或者,您可以在全局级别创建自己的对象,并使用匿名函数(创建闭包)包装文件,这样就不会污染全局命名空间。
// you can add other methods to it according to your use case.
window.MyPlugins = {
plugins: [],
registerPlugin: function (plugin){
this.plugins.push(plugin);
}
}
// MyFirstPlugin.js
// you can inject this code via creating a script tag.
(function(w){ //closure
function MyFirstPlugin() {
this.myPrint = function (){
console.log('ya blew it');
}
}
w.MyPlugins.registerPlugin(new MyFirstPlugin());
})(window)
// get the reference to the plugin in some other file
window.MyPlugins.plugins
关于javascript - 我可以允许从客户端动态加载 JS 模块吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58178469/