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

TypeScript开发Chrome扩展:如何消除编译后多余的exports代码?

解决Chrome扩展中TypeScript编译后exports is not defined错误

核心原因

你当前的TypeScript配置使用了CommonJS模块系统,而Chrome扩展的浏览器运行环境不支持Node.js的exports/require模块语法,导致编译后的代码抛出ReferenceError。

修复步骤

1. 修改tsconfig.json的模块配置

更新compilerOptions,切换到浏览器原生支持的ES模块体系:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext", // 替换原CommonJS为ES模块
    "moduleResolution": "Bundler", // 适配浏览器模块解析逻辑
    "rootDir": "./",
    "outDir": "dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "strictNullChecks": true,
    "alwaysStrict": true,
    "skipLibCheck": true,
    "isolatedModules": true // 确保每个文件都是独立模块,避免全局冲突
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

2. 调整扩展Manifest配置

如果你的扩展脚本(背景页、内容脚本等)使用编译后的ES模块代码,需要在manifest.json中为对应脚本声明模块类型:
示例背景页配置:

{
  "background": {
    "service_worker": "dist/background.js",
    "type": "module"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["dist/content.js"],
      "type": "module"
    }
  ]
}

3. 修正源码拼写错误

你的TypeScript源码存在类型名拼写错误:UserxCreationDate应改为UserCreationDate,避免编译时类型报错:

async function cacheUserCreationDate(userCreationDate : UserCreationDate) : Promise<void> {
    
}

验证修复

重新执行编译命令npm run compile,此时编译后的代码会使用ES模块语法,不再生成Object.defineProperty(exports, "__esModule", ...)代码,exports is not defined错误将被解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 14:32:33