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

Chrome扩展中TypeScript文件导入失败,报exports未定义错误

解决Chrome扩展中TypeScript导入报错“exports is not defined”

问题根源

你的tsconfig.json将module设置为commonjs,但Chrome扩展运行在浏览器环境中,不支持Node.js的CommonJS模块规范(exports、require这类语法)。TypeScript编译后生成的代码包含exports相关逻辑,导致浏览器抛出未定义错误。

修复方案

1. 修改TypeScript编译配置

更新tsconfig.json的module选项为浏览器原生支持的ES模块格式,同时配置对应的模块解析策略:

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["es2016", "dom", "dom.iterable"],
    "module": "ESNext", // 切换为ES模块规范
    "moduleResolution": "bundler", // 适配现代构建工具,也可设为"node"
    "rootDir": "src",
    "typeRoots": [ "node_modules/@types" ],
    "resolveJsonModule": true,
    "sourceMap": true,
    "outDir": "dist",
    "noEmitOnError": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

2. 配置Chrome扩展清单文件

在manifest.json中,确保使用模块的脚本声明为module类型(以Manifest V3为例):

{
  "manifest_version": 3,
  "name": "你的扩展名称",
  "version": "1.0",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["dist/importer.js"],
      "type": "module" // 声明该脚本为ES模块
    }
  ],
  "background": {
    "service_worker": "dist/background.js" // Manifest V3的Service Worker默认支持ES模块
  }
}

3. 验证编译结果

修改配置后重新编译,生成的JS文件会使用ES模块的import语法,而非CommonJS的exports逻辑,示例:

import * as imports from "./imports.js";
imports.hello();

注:ES模块导入需要显式添加.js后缀,TypeScript会自动处理路径转换。

补充建议

如果你的扩展使用打包工具(如Webpack、Vite),保持module: "ESNext"即可,让打包工具负责最终的模块打包与兼容处理,能更好地适配浏览器环境并避免路径问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 22:16:08