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

Flutter项目执行flutterfire config时遇Firebase CLI JSON解析错误

FlutterFire CLI JSON解析错误及Firebase.js弹出问题解决

问题描述

此前可正常使用Flutter及Firebase,切换Firebase CLI配置方式后:

  • 已成功安装Firebase CLI、完成登录,firebase init和firebase projects:list均正常执行
  • dart pub global activate flutterfire_cli无报错
  • 但在项目根目录执行flutterfire config时,出现JSON解析错误:
    Failed to parse JSON response from Firebase CLI. JSON response: FormatException: Unexpected end of input (at character 1)
    
  • 同时编辑器自动弹出Firebase CLI的firebase.js入口文件(代码如下):
    #!/usr/bin/env node
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const semver = require("semver");
    const pkg = require("../../package.json");
    const nodeVersion = process.version;
    if (!semver.satisfies(nodeVersion, pkg.engines.node)) {
        console.error(`Firebase CLI v${pkg.version} is incompatible with Node.js ${nodeVersion} Please upgrade Node.js to version ${pkg.engines.node}`);
        process.exit(1);
    }
    const updateNotifierPkg = require("update-notifier-cjs");
    const clc = require("colorette");
    const marked_terminal_1 = require("marked-terminal");
    const updateNotifier = updateNotifierPkg({ pkg });
    const marked_1 = require("marked");
    marked_1.marked.use((0, marked_terminal_1.markedTerminal)());
    const node_path_1 = require("node:path");
    const triple_beam_1 = require("triple-beam");
    const node_util_1 = require("node:util");
    const fs = require("node:fs");
    const configstore_1 = require("../configstore");
    const errorOut_1 = require("../errorOut");
    const handlePreviewToggles_1 = require("../handlePreviewToggles");
    const logger_1 = require("../logger");
    const client = require("..");
    const fsutils = require("../fsutils");
    const utils = require("../utils");
    const winston = require("winston");
    let args = process.argv.slice(2);
    let cmd;
    function findAvailableLogFile() {
        const candidates = ["firebase-debug.log"];
        for (let i = 1; i < 10; i++) {
            candidates.push(`firebase-debug.${i}.log`);
        }
        for (const c of candidates) {
            const logFilename = (0, node_path_1.join)(process.cwd(), c);
            try {
                const fd = fs.openSync(logFilename, "r+");
                fs.closeSync(fd);
                return logFilename;
            }
            catch (e) {
                if (e.code === "ENOENT") {
                    return logFilename;
                }
            }
        }
        throw new Error("Unable to obtain permissions for firebase-debug.log");
    }
    const logFilename = findAvailableLogFile();
    if (!process.env.DEBUG && args.includes("--debug")) {
        process.env.DEBUG = "true";
    }
    process.env.IS_FIREBASE_CLI = "true";
    logger_1.logger.add(new winston.transports.File({
        level: "debug",
        filename: logFilename,
        format: winston.format.printf((info) => {
            const segments = [info.message, ...(info[triple_beam_1.SPLAT] || [])].map(utils.tryStringify);
            return `[${info.level}] ${(0, node_util_1.stripVTControlCharacters)(segments.join(" "))}`;
        }),
    }));
    logger_1.logger.debug("-".repeat(70));
    logger_1.logger.debug("Command:      ", process.argv.join(" "));
    logger_1.logger.debug("CLI Version:  ", pkg.version);
    logger_1.logger.debug("Platform:     ", process.platform);
    logger_1.logger.debug("Node Version: ", process.version);
    logger_1.logger.debug("Time:         ", new Date().toString());
    if (utils.envOverrides.length) {
        logger_1.logger.debug("Env Overrides:", utils.envOverrides.join(", "));
    }
    logger_1.logger.debug("-".repeat(70));
    logger_1.logger.debug();
    const experiments_1 = require("../experiments");
    const fetchMOTD_1 = require("../fetchMOTD");
    (0, experiments_1.enableExperimentsFromCliEnvVariable)();
    (0, fetchMOTD_1.fetchMOTD)();
    process.on("exit", (code) => {
        code = process.exitCode || code;
        if (!process.env.DEBUG && code < 2 && fsutils.fileExistsSync(logFilename)) {
            fs.unlinkSync(logFilename);
        }
        if (code > 0 && process.stdout.isTTY) {
            const lastError = configstore_1.configstore.get("lastError") || 0;
            const timestamp = Date.now();
            if (lastError > timestamp - 120000) {
                let help;
                if (code === 1 && cmd) {
                    help = "Having trouble? Try " + clc.bold("firebase [command] --help");
                }
                else {
                    help = "Having trouble? Try again or contact support with contents of firebase-debug.log";
                }
                if (cmd) {
                    console.log();
                    console.log(help);
                }
            }
            configstore_1.configstore.set("lastError", timestamp);
        }
        else {
            configstore_1.configstore.delete("lastError");
        }
        try {
            const installMethod = !process.env.FIREPIT_VERSION ? "npm" : "automatic script";
            const updateCommand = !process.env.FIREPIT_VERSION
                ? "npm install -g firebase-tools"
                : "curl -sL https://firebase.tools | upgrade=true bash";
            const updateMessage = `Update available ${clc.gray("{currentVersion}")} → ${clc.green("{latestVersion}")}\n` +
                `To update to the latest version using ${installMethod}, run\n${clc.cyan(updateCommand)}\n` +
                `For other CLI management options, visit the ${(0, marked_1.marked)("[CLI documentation](https://firebase.google.com/docs/cli#update-cli)")}`;
            updateNotifier.notify({ defer: false, isGlobal: true, message: updateMessage });
        }
        catch (err) {
            logger_1.logger.debug("Error when notifying about new CLI updates:");
            if (err instanceof Error) {
                logger_1.logger.debug(err);
            }
            else {
                logger_1.logger.debug(`${err}`);
            }
        }
    });
    process.on("uncaughtException", (err) => {
        (0, errorOut_1.errorOut)(err);
    });
    if (!(0, handlePreviewToggles_1.handlePreviewToggles)(args)) {
        cmd = client.cli.parse(process.argv);
        args = args.filter((arg) => !arg.includes("-"));
        if (!args.length) {
            client.cli.help();
        }
    }
    

已尝试新建项目、更换Firebase账号及网络上常见解决方案,均无进展。

解决方案

1. 匹配Node.js与Firebase CLI版本

从firebase.js代码可见,Firebase CLI对Node.js版本有强制要求,版本不匹配会直接终止执行,导致FlutterFire CLI无法获取有效JSON响应:

  • 执行firebase --version查看当前CLI版本
  • 执行npm view firebase-tools@<你的CLI版本> engines.node查询对应Node.js版本要求
  • 使用Node版本管理器(如nvm)切换到匹配的Node.js版本

2. 完全重置CLI环境

残留的缓存或旧版本冲突可能导致异常,执行以下步骤彻底重置:

  • 卸载FlutterFire CLI:
    dart pub global deactivate flutterfire_cli
    
  • 卸载Firebase CLI:
    npm uninstall -g firebase-tools
    
  • 清理缓存:
    npm cache clean --force
    dart pub cache clean
    
  • 重新安装最新稳定版:
    npm install -g firebase-tools
    dart pub global activate flutterfire_cli
    
  • 重新登录Firebase账号:
    firebase login
    

3. 指定Firebase CLI路径

系统中存在多个Firebase CLI实例时,FlutterFire可能调用到错误的版本:

  • Linux/macOS执行which firebase,Windows执行where firebase获取正确CLI路径
  • 执行flutterfire config时指定路径:
    flutterfire config --firebase-cli-path="/path/to/firebase"
    

4. 禁用干扰性CLI特性

更新提示或实验特性可能破坏输出格式,导致JSON解析失败:

  • 执行命令时禁用更新提示:
    flutterfire config --no-update-notifier
    
  • 禁用所有实验特性:
    firebase experiments:disable all
    

5. 手动生成配置文件

如果以上方法均无效,可跳过CLI工具,手动创建firebase_options.dart:

  • 从Firebase控制台下载对应平台的配置文件(Android为google-services.json,iOS为GoogleService-Info.plist)
  • 参考官方配置格式,手动编写firebase_options.dart文件,填入项目的API密钥、项目ID等核心信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 09:27:03