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

Webpack项目Firebase模块导入报错求助:Uncaught TypeError

解决Uncaught TypeError: Failed to resolve module specifier 'firebase/app'错误

错误信息

Uncaught TypeError: Failed to resolve module specifier 'firebase/app'. Relative references must start with either '/', './', or '../'

引发错误的导入语句:

import { initializeApp } from 'firebase/app';

错误原因

你直接通过file://协议打开了src文件夹下的index.html文件——浏览器原生ES模块机制不支持解析npm包的"裸导入"(比如firebase/app这种不带相对/绝对路径的模块名)。而dist文件夹里的文件是经过Webpack打包后的产物,Webpack已经把所有npm模块依赖转换成了浏览器能识别的代码,所以直接打开dist的html不会报错。

解决步骤

  • 使用Webpack Dev Server运行项目

    1. 安装开发服务器依赖:
      npm install webpack-dev-server --save-dev
      
    2. 在项目根目录的package.json的scripts字段中添加启动命令:
      "scripts": {
        "start": "webpack serve --mode development",
        "build": "webpack --mode production"
      }
      
    3. 执行npm start启动开发服务器,通过http://localhost:8080(默认端口)访问应用,不要直接打开本地html文件。
  • 验证Webpack配置正确性
    确保你的webpack.config.js配置了正确的入口和出口,示例配置如下:

    const path = require('path');
    
    module.exports = {
      mode: 'development',
      entry: './src/index.js',
      output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist'),
      },
    };
    

    Webpack会自动处理node_modules中的依赖包,将裸导入转换为浏览器可识别的模块引用。

  • 禁止直接访问src目录下的HTML文件
    浏览器的file://协议不支持npm包的模块解析逻辑,必须通过HTTP服务器(开发服务器或生产环境静态服务器)访问应用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:30:17