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

使用Vite构建React浏览器扩展:background与content脚本配置问题

解决方案

1. 调整项目结构

把content和background脚本放在src下独立的入口目录,避免被打包到主index.js中:

src/
├── background/
│   └── background.jsx
├── content/
│   └── content.jsx
├── App.jsx
└── main.jsx (原主入口,用于popup或其他页面)

2. 配置Vite多入口打包

修改vite.config.js,添加多入口配置,让Vite单独打包content和background脚本:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  build: {
    rollupOptions: {
      input: {
        // 主入口(若需popup页面则保留)
        main: './index.html',
        // content脚本入口
        content: './src/content/content.jsx',
        // background脚本入口
        background: './src/background/background.jsx'
      },
      output: {
        // 输出文件名与入口对应
        entryFileNames: '[name].js',
        chunkFileNames: '[name].js',
        assetFileNames: '[name].[ext]'
      }
    }
  }
})

执行npm run build后,dist目录会生成独立的content.js、background.js文件。

3. 配置manifest.json(以V3为例)

修改manifest文件,引用打包后的脚本路径:

{
  "manifest_version": 3,
  "name": "Your Extension",
  "version": "1.0",
  "content_scripts": [
    {
      "matches": ["<all_urls>"], // 替换为你需要注入的页面规则
      "js": ["content.js"]
    }
  ],
  "background": {
    "service_worker": "background.js"
  },
  // 若有popup页面,添加以下配置
  "action": {
    "default_popup": "index.html"
  }
}

如果使用Manifest V2,background配置改为:

"background": {
  "scripts": ["background.js"]
}

4. 验证content脚本代码

你的content.jsx代码无需修改,Vite会自动将JSX编译为浏览器可识别的JS代码。打包后的content.js会包含React、ReactDOM及App组件逻辑,注入匹配页面后会自动渲染弹窗。

5. 测试扩展

  1. 执行npm run build生成dist目录
  2. 打开浏览器扩展管理页面(如chrome://extensions/)
  3. 开启「开发者模式」,点击「加载已解压的扩展程序」,选择dist目录
  4. 访问匹配页面,检查App组件是否成功渲染

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 18:25:04