Firefox使用import assert导入JSON报错,Chrome等浏览器运行正常
解决Firefox中JSON导入的SyntaxError问题
问题原因
你遇到的错误是因为import insurances from './insurances.json' assert {type: 'json'}里的**导入断言(import assertions)**语法在旧版Firefox中未被支持,而Chrome、Edge、Opera更早适配了该ES提案,所以能正常运行。Firefox从版本108开始才默认支持导入断言,低于这个版本的浏览器会抛出SyntaxError: unexpected token: identifier。
解决方案
1. 升级Firefox版本
将Firefox升级到108或更高版本,即可原生支持该导入语法,无需修改代码。
2. 改用Fetch API(兼容旧版Firefox)
如果需要兼容低版本Firefox,用fetch替代ES模块导入JSON,这是所有现代浏览器都支持的方案:
// 替换原import语句 fetch('./insurances.json') .then(res => res.json()) .then(insurances => { // 原forEach逻辑 insurances.forEach(e => { // 你的业务代码 }); }) .catch(err => console.error('JSON加载失败:', err));
3. 借助构建工具处理(适用于项目使用Webpack/Vite等)
如果你的项目用了构建工具,直接去掉assert {type: 'json'},构建工具会自动处理JSON导入:
import insurances from './insurances.json'
Webpack、Vite等工具默认支持JSON导入,编译后的代码会兼容包括旧版Firefox在内的所有浏览器。
内容的提问来源于stack exchange,提问作者Kuba Bujak
相关产品推荐
相关产品推荐

