问题描述
在我的WebExtension的后台脚本中,我想使用另一个JavaScript文件中的函数/常量。但是听起来很简单,但我无法使其正常工作。
-
manifest.json
:{ "manifest_version": 2,"name": "MinimalCompleteReproducibleExample","version": "0.0.0.0","background": { "page": "background.html" } }
-
background.html
:<!DOCTYPE html> <html> <head> <Meta charset="UTF-8"> </head> <body> <script type="module" src="/mylib.js"></script> <script src="background.js"></script> </body> </html>
它会加载“外部” JavaScript文件
mylib.js
,其中包含我要重用的函数/常量以及实际的后台脚本background.js
。 -
mylib.js
:export const foo = 42;
它仅导出常量
foo
。 -
background.js
:console.log(foo);
加载此扩展名时,在调试器中收到以下错误消息:
Uncaught ReferenceError: foo is not defined
这似乎表明mylib.js
的内容不可用。
在此之前,我确实将background.js
直接加载到manifest.json
中,并将以下行添加到background.js
中:
import { foo } from "/mylib.js";
但这似乎在WebExtensions中是不允许的,并且也不起作用:
Uncaught SyntaxError: import declarations may only appear at top level of a module
那么有人可以告诉我,如何在后台脚本中提供另一个JavaScript文件吗?
解决方法
wOxxOm's comment帮助我解决了这个问题。必须进行两项更改:
- 在
type="module"
中将<script src="background.js"></script>
添加到background.html
- 将
import { foo } from "/mylib.js";
添加到background.js
然后可以省略<script type="module" src="/mylib.js"></script>
中的行background.html
。
完整的工作示例:
-
manifest.json
:{ "manifest_version": 2,"name": "MinimalCompleteReproducibleExample","version": "0.0.0.0","background": { "page": "background.html" } }
-
background.html
:<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <script type="module" src="/background.js"></script> </body> </html>
-
mylib.js
:export const foo = 42;
-
background.js
:import { foo } from "/mylib.js"; console.log(foo);