如何在Firefox WebExtension的后台脚本中导入/使用外部JavaScript文件?
在WebExtension的后台脚本中,我想使用另一个JavaScript文件中的函数/常量。虽然听起来很简单,但我无法让它工作 我使用以下四个文件作为我的问题的最小示例:如何在Firefox WebExtension的后台脚本中导入/使用外部JavaScript文件?,javascript,firefox-addon-webextensions,Javascript,Firefox Addon Webextensions,在WebExtension的后台脚本中,我想使用另一个JavaScript文件中的函数/常量。虽然听起来很简单,但我无法让它工作 我使用以下四个文件作为我的问题的最小示例: manifest.json: { "manifest_version": 2, "name": "MinimalCompleteReproducibleExample", "version": "0.0.0.0&
manifest.json
:
{
"manifest_version": 2,
"name": "MinimalCompleteReproducibleExample",
"version": "0.0.0.0",
"background": {
"page": "background.html"
}
}
{
"manifest_version": 2,
"name": "MinimalCompleteReproducibleExample",
"version": "0.0.0.0",
"background": {
"page": "background.html"
}
}
它基本上只是加载background.html
作为后台脚本/页面
background.html
:
它加载“外部”JavaScript文件mylib.js
,其中包含我要重用的函数/常量以及实际的后台脚本background.js
mylib.js
:
export const foo=42;
它只导出常量foo
background.js
:
console.log(foo);
它尝试使用“外部”JavaScript文件mylib.js
的内容
未捕获引用错误:未定义foo
这似乎表明mylib.js
的内容不可用
在此之前,我确实直接在manifest.json
中加载了background.js
,并在background.js
中添加了以下行:
从“/mylib.js”导入{foo};
但这在WebExtensions中似乎是不允许的,也不起作用:
未捕获语法错误:导入声明只能出现在模块的顶层
有人能告诉我,如何在后台脚本中使用另一个JavaScript文件吗?帮助我解决了这个问题。有两项改变是必要的:
- 将
添加到type=“module”
background.html中的
- 添加了“/mylib.js”中的
到import{foo}”
background.js
background.html
中的
行
完整的工作示例:
manifest.json
:
{
"manifest_version": 2,
"name": "MinimalCompleteReproducibleExample",
"version": "0.0.0.0",
"background": {
"page": "background.html"
}
}
background.html
:
mylib.js
:
export const foo=42;
background.js
:
从“/mylib.js”导入{foo};
console.log(foo);
将
type=“module”
添加到您的后台脚本声明中。请注意,在Firefox扩展中使用远程脚本将导致AMO拒绝该扩展。@erosman感谢您的建议。幸运的是,我不打算动态地把它拉进来。我将在分机内运送图书馆。