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

Firebase V8云存储上传代码迁移至V9及模块找不到报错求助

报错原因

你遇到的模块找不到报错,是因为混用了Firebase V9的CDN导入语法和本地npm包的导入逻辑,原V8版本的require("firebase/firebase-storage")这类全局挂载式导入在V9模块化版本中已废弃,你安装了V9版本的依赖却沿用V8的导入规则,才会触发资源找不到的错误。

完整迁移后的Firebase V9(模块化写法)代码

前提是你已经在项目中完成了Firebase V9的初始化配置(调用过initializeApp传入你的项目配置):

// 导入需要的模块化API
import { getAuth } from "firebase/auth";
import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
// 若当前文件用到firestore,单独导入对应API即可,不需要全局引入

const uploadImage = async () => {
    const uri = props.route.params.image;
    const currentUser = getAuth().currentUser;
    if(!currentUser) return; // 增加用户登录校验避免空值报错
    const childPath = `post/${currentUser.uid}/${Math.random().toString(36)}`;
    console.log(childPath);

    const response = await fetch(uri);
    const blob = await response.blob();

    // 初始化存储实例、创建存储引用
    const storage = getStorage();
    const storageRef = ref(storage, childPath);
    const uploadTask = uploadBytesResumable(storageRef, blob);

    // 监听上传状态
    uploadTask.on('state_changed', 
        (snapshot) => {
            // 上传进度回调
            console.log(`transferred: ${snapshot.bytesTransferred}`)
        }, 
        (error) => {
            // 上传错误回调
            console.log(error)
        }, 
        () => {
            // 上传完成回调,获取文件下载链接
            getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
                savePostData(downloadURL);
                console.log(downloadURL)
            });
        }
    );
}

额外修复步骤

  • 删掉原有代码中require("firebase/firestore")、require("firebase/firebase-storage")两行全局引入代码,V9全部采用模块化按需导入
  • 检查package.json中的firebase依赖版本,确认不存在V8、V9版本共存的冲突情况
  • 如果你需要沿用V8的写法做渐进式迁移,请改用compat兼容路径导入:import 'firebase/compat/storage'、import 'firebase/compat/firestore',不要直接导入firebase/xxx路径

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:06:04