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

Webpack多入口点报错:Uncaught ReferenceError: Chatroom未定义

问题原因

Webpack 默认会把每个入口文件的代码包裹在独立的模块作用域里(类似自执行函数),不会自动将内部定义的类、变量暴露到全局 window 对象。所以哪怕你在HTML里按顺序引入打包文件,app.bundle.js 也没法直接访问 chat.bundle.js 里的 Chatroom 类。

解决方案

方法1:手动挂载到全局(快速临时方案)

修改 chat.js,把 Chatroom 直接挂载到 window 上:

class Chatroom {
  constructor (room, username){
    this.room = room;
    this.username = username;
    this.chats = colRef;
    this.unsub;
  }
}
// 手动暴露到全局作用域
window.Chatroom = Chatroom;

这样 app.js 里就能直接实例化 Chatroom 了。

方法2:用Webpack配置自动暴露模块(规范全局暴露方式)

修改Webpack配置,给 chat 入口添加 library 配置,让Webpack自动把模块内容暴露到全局:

const webpack = require('webpack');
const path = require('path');

const config = {
  mode: 'development',
  entry: {
    app: './src/app/app.js',
    chat: './src/chat/chat.js',
    ui: './src/ui/ui.js'
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].bundle.js',
    // 给chat入口配置全局暴露规则
    library: {
      name: '[name]', // 模块会被暴露为 window.chat
      type: 'window'
    }
  },
  watch: true
};

module.exports = config;

然后修改 chat.js 导出类:

export class Chatroom {
  constructor (room, username){
    this.room = room;
    this.username = username;
    this.chats = colRef;
    this.unsub;
  }
}

在 app.js 里通过全局对象访问:

const chatroom = new window.chat.Chatroom('general', 'dan');

方法3:ES模块导入导出(推荐的模块化方案)

这是Webpack的标准用法,抛弃全局作用域,改用模块依赖管理:

  1. 修改 chat.js 导出类:
export class Chatroom {
  constructor (room, username){
    this.room = room;
    this.username = username;
    this.chats = colRef;
    this.unsub;
  }
}
  1. 在 app.js 中直接导入:
import { Chatroom } from '../chat/chat.js';

const chatroom = new Chatroom('general', 'dan');
  1. 调整Webpack入口,只保留 app 作为主入口(Webpack会自动处理所有依赖):
const webpack = require('webpack');
const path = require('path');

const config = {
  mode: 'development',
  entry: {
    app: './src/app/app.js'
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].bundle.js'
  },
  watch: true
};

module.exports = config;

最后HTML里只需要引入 app.bundle.js 即可,Webpack会把所有依赖打包进这个文件。

总结
  • 方法1适合快速调试,但全局变量易引发命名冲突,不建议生产环境使用。
  • 方法2适合必须保持多入口且需要全局暴露的场景。
  • 方法3是Webpack推荐的模块化写法,代码更清晰、可维护,优先推荐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 11:47:15