Javascript 是否将函数动态导入ES5JS文件?
这可能看起来有点复杂,所以如果有,我会提前道歉。 我试图在Node.js中为Chrome扩展创建一个构建工具,因此最终的js文件必须符合ES5 对于导出对象的扩展中的每个设置,我都有单独的JS文件,这个对象中的函数需要导入到contentScript.JS文件中,并放置在它自己的设置对象中 我已经整理了一份报告来说明这应该如何进行,但我不确定如何处理这个问题。我已经考虑过contentScript中的某种类型的字符串插值,然后节点将替换它,但这似乎更像是一种解决方法,而不是解决方案 假设我们有一个名为settings的文件夹,在这些设置中有两个JavaScript文件,每个文件都有不同的名称、类型和功能,它们看起来像这样Javascript 是否将函数动态导入ES5JS文件?,javascript,node.js,Javascript,Node.js,这可能看起来有点复杂,所以如果有,我会提前道歉。 我试图在Node.js中为Chrome扩展创建一个构建工具,因此最终的js文件必须符合ES5 对于导出对象的扩展中的每个设置,我都有单独的JS文件,这个对象中的函数需要导入到contentScript.JS文件中,并放置在它自己的设置对象中 我已经整理了一份报告来说明这应该如何进行,但我不确定如何处理这个问题。我已经考虑过contentScript中的某种类型的字符串插值,然后节点将替换它,但这似乎更像是一种解决方法,而不是解决方案 假设我们有一
// settingName1.js
module.exports = {
name: 'Setting Name 1',
type: 'switch',
function: () => {
console.log('Setting 1 initialized');
}
}
理想情况下,这两个文件都将各自的函数导入到contentScript中,例如设置对象下
// contentScript.js
// Settings Functions Go Here
const settings = {
settingName1: function() {
console.log('Setting 1 initialized')
},
settingName2: function() {
console.log('Setting 2 initialized')
}
}
});
基本上是从源设置文件本身剪切/复制函数,并将其粘贴到contentScript的设置对象中的函数(使用文件名命名)下。以下是生成文件的想法:
// header on the file
const capturedExports = [];
// insert this prologue before each inserted file
(function() {
// =============================
// insert settingName1.js here
module.exports = {
name: 'Setting Name 1',
type: 'switch',
function: () => {
console.log('Setting 1 initialized');
}
}
// =============================
// insert this epilogue after each inserted file
})();
capturedExports.push(module.exports);
// insert this prologue before each inserted file
(function() {
// =============================
// insert settingName2.js here
module.exports = {
name: 'Setting Name 2',
type: 'switch',
function: () => {
console.log('Setting 2 initialized');
}
}
// =============================
// insert this epilogue after each inserted file
})();
capturedExports.push(module.exports);
// insert code that builds the settings object
const settings = {};
for (let exportItem of capturedExports) {
let name = exportItem.name.replace(/\s/, "");
name = name.slice(0, 1).toLowerCase() + name.slice(1);
settings[name] = exportItem.function;
}
执行以下步骤以输出一个新文件,该文件是所有settingNamex.js
文件的集合
constcapturedexports=[]向其写入一个头代码>行和生命的开始
settingNameX.js
文件,将该文件写入其中模块的任何代码。导出
,并将其添加到caputuredExports
数组中settingNameX.js
文件重复此过程capturedExports
数组构建设置对象的代码settingNameX.js
文件的代码将适当的对象分配给module.exports
,如示例所示。在现实世界中,您可能需要添加一系列测试,以查看是否为module.exports分配了正确的内容(正确的防御性编码)模块。导出
,或者在插入的模块使用它之后可以在最后覆盖它。如果此假设不正确,则必须手动将module.exports=
更改为在主模块中定义的其他内容如果问题中的文件使用的是
module.exports
,那么为什么不干脆require()
将它们导入,抓取它们导出的对象,并从它们导出的对象将您想要的功能分配到公共设置对象上呢?如果要了解如何在设置对象上确定要将它们指定给哪个属性名,则可以使用导出的name
属性获取该属性或从中派生属性名。除此之外,我不明白你的问题是什么。另外,请将你的图像直接嵌入到你的帖子中,而不仅仅是作为一个外部链接,这样它更容易被看到,并且不会在imgur.com过期时消失。@jfriend00有一个新帐户,我无法直接嵌入图像,如果可以的话,我会的。我试图要求它,但这总是导致最终的contentScript文件试图从Chrome中要求它,这返回了一个“require is not defined”错误,因为浏览器还不支持它。所以我需要将这个函数导入并编译到文件中,如果你愿意的话,我想我不明白你想要得到的最终结果是什么。您能否显示(粘贴到问题中并格式化为代码)最终生成的文本文件应该是什么样子?