You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firefox和Chrome扩展:如何在background脚本中使用import语法?

解决Firefox与Chrome扩展背景脚本的ES模块导入问题

Firefox 配置调整

Firefox 默认将 background.scripts 下的脚本当作普通脚本而非ES模块,直接使用import会触发报错。只需在manifest的background配置中添加type: "module"声明,将脚本转为模块模式即可:

"background": {
  "scripts": ["scripts/background.js"],
  "type": "module"
},

修改后,background.js就能正常使用import语句导入模块。

Chrome 配置调整

Chrome的Service Worker本身支持ES模块,但默认按普通脚本处理,同样需要显式声明模块类型:

"background": {
  "service_worker": "scripts/service-worker.js",
  "type": "module"
},

添加type: "module"后,service-worker.js即可使用import导入工具模块。

路径注意事项

确保import的路径是相对当前脚本的正确路径:

  • 若background.js和utils.js都在scripts目录下,导入语句应为:
    import { thing } from './utils.js';
    
  • 避免使用绝对路径或错误的层级路径,否则会出现模块找不到的错误。

内容的提问来源于stack exchange,提问作者chovy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 18:58:12