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

Chrome扩展Content Script报错(React+Vite):Cannot use import statement outside a module

解决Chrome扩展Content Script中"Cannot use import statement outside a module"错误

针对你用React+Vite开发扩展时遇到的这个问题,按以下步骤配置即可解决:

1. 调整Vite构建配置

在vite.config.ts中修改build选项,确保Rollup将Content Script打包为ES模块,并指定正确的入口文件:

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

export default defineConfig({
  plugins: [react()],
  build: {
    rollupOptions: {
      input: {
        // 指定content script的入口文件路径
        content: './src/ContentScript.tsx',
        // 如有其他入口(比如popup、background)可在此添加
      },
      output: {
        format: 'es', // 输出ES模块格式
        entryFileNames: '[name].js', // 保持文件名对应,方便manifest引用
      },
    },
  },
});

2. 修改扩展Manifest配置(Chrome V3)

在manifest.json中,将Content Script的type设置为module,同时指定打包后的脚本路径:

{
  "manifest_version": 3,
  "content_scripts": [
    {
      "matches": ["<all_urls>"], // 根据需求调整匹配规则
      "js": ["dist/content.js"], // 对应Vite打包后的文件路径
      "type": "module" // 关键:声明这是ES模块脚本
    }
  ],
  // 其他扩展配置(name、version等)
}

3. 验证依赖与编译

  • 确保已安装@vitejs/plugin-react插件:
    npm install @vitejs/plugin-react --save-dev
    
  • 执行构建命令:
    npm run build
    
  • 重新加载扩展到Chrome中,检查错误是否消失。

额外注意点

  • 若使用Chrome Manifest V2,V2不支持ES模块的Content Script,需将Vite输出格式改为iife并移除manifest中的type字段:
    // vite.config.ts中修改output.format
    output: {
      format: 'iife',
      entryFileNames: '[name].js',
    }
    
  • 确认Content Script未使用Node.js环境API,扩展的Content Script运行在隔离环境中,不支持Node.js模块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 14:52:35