首次使用Firebase Web开发出现unexpected token 'export'错误求解决
问题原因
你遇到的unexpected token 'export'报错由两个问题共同导致:
- Firebase 9.x版本默认提供的CDN资源是ES Module格式,普通script标签无法识别ES模块的
export语法,直接引入就会触发该错误 - HTML规范中script标签不支持自闭合写法,你写的
<script src="xxx"/>会被浏览器错误解析,导致后续脚本执行异常
修复方案
直接使用Firebase 9提供的兼容版本CDN资源即可,兼容版本同时支持传统script标签引入和老版本的命名空间调用语法,不需要修改你现有的业务代码逻辑,只需要调整两处:
- 所有firebase资源的CDN路径增加
-compat后缀 - 修正script标签的闭合写法,补充单独的
</script>闭合标签
修复后完整代码
<!DOCTYPE html> <html> <head> <title> Firebase Demo </title> <script src="https://www.gstatic.com/firebasejs/9.0.2/firebase-app-compat.js"></script> <script src="https://www.gstatic.com/firebasejs/9.0.2/firebase-auth-compat.js"></script> <script src="https://www.gstatic.com/firebasejs/9.0.2/firebase-database-compat.js"></script> <script> const firebaseConfig = { // 替换为你的真实Firebase配置信息 }; // Initialize Firebase const app = firebase.initializeApp(firebaseConfig); const database = firebase.database(); database.ref("List/"+"Targets").set({ name:"niel", state:"alive" }); </script> </head> <body> <h1 align="center">Firebase Jinx</h1> </body> </html>
如果你想要使用Firebase 9原生的模块化API,只需要将script标签的type属性设置为module,通过import语法导入对应方法即可,无需使用兼容包。
内容的提问来源于stack exchange,提问作者Bhushan Patil
相关产品推荐
相关产品推荐

