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

运行firebase serve时部分JavaScript代码不执行问题

问题修复方案

  • 首先确认你修改的JS文件是firebase托管目录下的文件:打开firebase.json查看hosting.public字段对应的目录,进入该目录找到你引用的JS文件,检查末尾的按钮逻辑是否存在。如果不存在说明你修改的是其他目录的源码,没有同步到托管目录,需要配置构建流程自动同步源码到public目录。
  • 运行serve时禁用缓存:执行命令 firebase serve --no-cache,同时打开浏览器开发者工具的Network面板,勾选「Disable cache」后刷新页面,排除资源缓存导致加载旧版不完整JS的问题。
  • 修正JS文件中的语法错误:你提供的代码示例中箭头函数被转义为() =>,如果实际JS文件中存在该转义字符,会直接触发语法错误,导致JS执行到错误位置后中断,后续代码不会生效,需要将所有>替换为>。
  • 调整JS代码执行时机:将所有JS逻辑包裹在DOM加载完成的回调中,避免firebase serve加载资源顺序差异导致提前执行找不到DOM元素抛出异常:
document.addEventListener('DOMContentLoaded', () => {
  // 原有所有JS代码放在此处内部
  const requestModal = document.querySelector('.new-request');
  const requestBtn = document.querySelector('.add-request');

  requestBtn.addEventListener('click', () => {
    requestModal.classList.add('open');
  });
  requestModal.addEventListener('click', (e) => {
    if(e.target.classList.contains('new-request')){
        requestModal.classList.remove('open');
    }else{
        alert('This is a modal, click on the outside to close it.');
        alert('Modal Closed');
    }
  });

  // say hello function call
  const button = document.querySelector('.callBtn');
  button.addEventListener('click', () => {
    alert('What are you');
    // get function reference
    const sayHello = firebase.functions().httpsCallable('sayHello');
    sayHello().then(result => {
        console.log(result.data);
    });
  });
})
  • 调整firebase托管配置:在firebase.json中添加JS资源的无缓存规则,避免本地开发时缓存异常:
{
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "headers": [
      {
        "source": "**/*.js",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "no-store, no-cache, must-revalidate"
          }
        ]
      }
    ]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 00:54:05