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

博客发布按钮触发Uncaught ReferenceError: firebase未定义问题求助

错误根源

你使用的是Firebase 9+模块化API,不存在全局firebase对象,editor.js里的firebase.firestore()调用自然找不到;同时editor.js未以模块方式加载,无法导入firebase.js中初始化好的db实例。


修复步骤

1. 调整editor.js代码

将editor.js改为模块,导入firebase.js的db实例,并使用Firebase 9的模块化方法写入数据:

import { db } from './firebase.js';
import { setDoc, doc } from "https://www.gstatic.com/firebasejs/9.20.0/firebase-firestore.js";

const blogTitleField = document.querySelector('.title');
const articleFeild = document.querySelector('.article');

// banner相关逻辑保持不变
const bannerImage = document.querySelector('#banner-upload');
const banner = document.querySelector(".banner");
let bannerPath;

const publishBtn = document.querySelector('.publish-btn');
const uploadInput = document.querySelector('#image-upload');

bannerImage.addEventListener('change', () => {
    uploadImage(bannerImage, "banner");
})

uploadInput.addEventListener('change', () => {
    uploadImage(uploadInput, "image");
})

const uploadImage = (uploadFile, uploadType) => {
    const [file] = uploadFile.files;
    if(file && file.type.includes("image")){
        const formdata = new FormData();
        formdata.append('image', file);

        fetch('/upload', {
            method: 'post',
            body: formdata
        }).then(res => res.json())
        .then(data => {
            if(uploadType == "image"){
                addImage(data, file.name);
            } else{
                bannerPath = `${location.origin}/${data}`;
                banner.style.backgroundImage = `url("${bannerPath}")`;
            }
        })
    } else{
        alert("upload Image only");
    }
}

const addImage = (imagepath, alt) => {
    let curPos = articleFeild.selectionStart;
    let textToInsert = `\r![${alt}](${imagepath})\r`;
    articleFeild.value = articleFeild.value.slice(0, curPos) + textToInsert + articleFeild.value.slice(curPos);
}

let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

publishBtn.addEventListener('click', () => {
    if(articleFeild.value.length && blogTitleField.value.length){
        // 生成ID逻辑保持不变
        let letters = 'abcdefghijklmnopqrstuvwxyz';
        let blogTitle = blogTitleField.value.split(" ").join("-");
        let id = '';
        for(let i = 0; i < 4; i++){
            id += letters[Math.floor(Math.random() * letters.length)];
        }

        let docName = `${blogTitle}-${id}`;
        let date = new Date();

        // 替换为Firebase 9模块化写入方法
        setDoc(doc(db, "blogs", docName), {
            title: blogTitleField.value,
            article: articleFeild.value,
            bannerImage: bannerPath,
            publishedAt: `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`
        })
        .then(() => {
            location.href = `/${docName}`;
        })
        .catch((err) => {
            console.error(err);
        })
    }
})

2. 修改editor.html的脚本标签

将editor.js的脚本标签改为模块类型,确保能使用import语法:

<!-- 原代码 -->
<script type="module" src="js/firebase.js"></script>
<script src="./js/editor.js"></script>

<!-- 修改后 -->
<script type="module" src="js/firebase.js"></script>
<script type="module" src="./js/editor.js"></script>

3. 验证路径正确性

确保firebase.js和editor.js的相对路径正确,比如editor.js在js/目录下时,导入路径./firebase.js是正确的。


关键说明

Firebase 9+采用模块化设计,所有功能需通过导入对应函数使用,不再支持旧版全局firebase.firestore()调用方式。通过导入初始化好的db实例和setDoc、doc函数,即可正确完成数据写入操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:02:57