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

导入Firebase模块时出现SyntaxError Unexpected token '{'如何解决

问题原因与修复方案

错误根因

  • 静态import语句不允许在函数内部声明,只能放在模块的最顶层作用域,你在writeTest函数内写的import语句不符合ES模块语法规范,是触发本次语法报错的直接原因。
  • Firestore相关依赖的导入路径错误,你使用的是CDN版本的Firebase SDK,不能用npm包的导入路径"firebase/firestore",需要和firebase-app的导入保持一致,使用对应版本的CDN地址。
  • writeTest函数内使用了await关键字,但函数未声明async,语法问题修复后会触发新的运行时报错。
  • 缺少Firestore实例的初始化逻辑,代码中用到的db变量未定义。

修正后的完整代码

script.js 代码

// 所有静态import语句必须放在模块顶层
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
import { getFirestore, doc, setDoc, Timestamp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-firestore.js";
      
const firebaseConfig = {
  apiKey: "**",
  authDomain: "**",
  projectId: "**",
  storageBucket: "**",
  messagingSenderId: "**",
  appId: "**"
};

// 初始化Firebase与Firestore实例
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

// 使用await的函数必须添加async标识
async function writeTest() {
  const docData = {
      stringExample: "Hello world!",
      booleanExample: true,
      numberExample: 3.14159265,
      dateExample: Timestamp.fromDate(new Date("December 10, 1815")),
      arrayExample: [5, true, "hello"],
      nullExample: null,
      objectExample: {
          a: 5,
          b: {
              nested: "foo"
          }
      }
  };
  await setDoc(doc(db, "data", "one"), docData);
}

可选:按需动态导入写法

如果你确实需要在函数调用时才加载Firestore相关依赖,可以使用动态导入语法,不需要把import放在顶层:

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
import { getFirestore } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-firestore.js";
      
const firebaseConfig = {
  apiKey: "**",
  authDomain: "**",
  projectId: "**",
  storageBucket: "**",
  messagingSenderId: "**",
  appId: "**"
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

async function writeTest() {
  // 动态导入返回Promise,需要await接收导出内容
  const { doc, setDoc, Timestamp } = await import("https://www.gstatic.com/firebasejs/9.1.3/firebase-firestore.js");
  const docData = {
      stringExample: "Hello world!",
      booleanExample: true,
      numberExample: 3.14159265,
      dateExample: Timestamp.fromDate(new Date("December 10, 1815")),
      arrayExample: [5, true, "hello"],
      nullExample: null,
      objectExample: {
          a: 5,
          b: {
              nested: "foo"
          }
      }
  };
  await setDoc(doc(db, "data", "one"), docData);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:36:07