TypeScript开发Chrome扩展编译后JS报错:Unexpected token 'export'
解决Chrome扩展TypeScript转译后
Unexpected token 'export'报错 这个报错的核心原因是Chrome扩展的运行环境不识别你输出的模块语法,需要根据你的Manifest版本调整TypeScript配置和扩展声明文件:
针对Manifest V3(推荐)
Manifest V3支持ES模块,但需要明确声明模块类型:
1. 修改tsconfig.json配置
使用ESNext模块语法,配合Chrome支持的高版本ECMAScript目标:
{ "compilerOptions": { "target": "ES2020", // Chrome对ES2020支持完善,无需降级到ES5 "module": "ESNext", "moduleResolution": "NodeNext", // 优化模块解析逻辑 "outDir": "dist", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true }, "include": ["src/**/*"], // 替换为你的TS文件根目录 "exclude": ["node_modules"] }
2. 更新manifest.json
在根层级添加type: "module",并为content script单独声明模块类型:
{ "manifest_version": 3, "type": "module", // 全局声明模块类型 "background": { "service_worker": "dist/background.js" }, "content_scripts": [ { "matches": ["<all_urls>"], "js": ["dist/content.js"], "type": "module" // 为content script单独指定模块类型 } ], // popup/options页面的HTML中引用JS时,也要加type="module": // <script type="module" src="dist/popup.js"></script> // 其他扩展配置... }
针对Manifest V2(旧版本)
Manifest V2不支持ES模块和CommonJS,需要将代码转译为无模块的全局代码:
修改tsconfig.json配置
{ "compilerOptions": { "target": "ES5", "module": "None", // 禁用模块系统,转译为全局变量形式 "outDir": "dist", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true }, "include": ["src/**/*"], "exclude": ["node_modules"] }
关键说明
你之前尝试commonjs/ES6无效的原因:
- Chrome扩展的content script、background环境不支持CommonJS的
require语法 - ES模块语法需要Manifest V3中明确声明
type: "module",否则Chrome会将其视为普通脚本,无法识别export关键字
内容的提问来源于stack exchange,提问作者fuyi
相关产品推荐
相关产品推荐

