实例化 es6 类

instantiating an es6 class

本文关键字:es6 实例化      更新时间:2023-09-26

我正在尝试使用 es6 来制作聊天室连接类。我正在使用 rabbitmq/STOMP 将交换数据推送给订阅者。我使用的代码以 es5 风格工作,但我正在硬编码交换名称。我正在使用 webpack/babel 在一个名为 chat.bundle.js 的文件中将此代码转写回 es5,但是当我运行时:

var chatRoom = new ChatRoom('thisExchange');

控制台日志:Uncaught ReferenceError: ChatRoom is not defined

我在加载捆绑包文件后实例化类ChatRoom(在捆绑包的此脚本标记下方(。

我知道load()功能可能不起作用...我是 es6 类的新手,不确定如何让 window.load 工作,但这是一个单独的问题。现在,我只想能够通过提供exchangeName的参数来实例化这个类,然后在此之后继续处理新的错误。

这是我写得很糟糕的 es6 类:

// Use SockJS
Stomp.WebSocketClass = SockJS;
// Connection parameters
var mq_username = "guest",
mq_password = "guest",
mq_vhost    = "/",
mq_url      = 'http://localhost:15674/stomp',
mq_queue    = "/exchange/${this.exchange}";
var output;
var client = Stomp.client(mq_url);
class ChatRoom {
    constructor(exchange){
        this._exchange=exchange;
    }
    get exchange(){
        return this._exchange;
    }
    toString() {
        return `${this.exchange}`
    }
    on_connect() {
    output.innerHTML += 'Connected to RabbitMQ-Web-Stomp<br />';
    console.log(client);
    client.subscribe(mq_queue, on_message);
}
// This will be called upon a connection error
    on_connect_error() {
        output.innerHTML += 'Connection failed!<br />';
    }
// This will be called upon arrival of a message
on_message(m) {
    console.log('message received');
    console.log(m);
    output.innerHTML += m.body + '<br />';
}
load(){
    return new Promise(function(resolve,reject){
        window.onload =  () => {
            // Fetch output panel
            output = document.getElementById("output");
            // Connect
            client.connect(
                self.mq_username,
                self.mq_password,
                self.on_connect,
                self.on_connect_error,
                self.mq_vhost
            );
        }
    });
}

}

在我的 html 文件中,脚本标签的结构如下:

<script src="static/chat.bundle.js"></script>
<script>var chatRoom=new ChatRoom('soccer@newark');</script>

Webpack 构建成功,并且不抱怨聊天捆绑包的 es6 文件的语法,如上所示。

通常,像 webpack 这样的模块捆绑器不会公开模块局部变量。如果要将类ChatRoom导出为公共 API,请在文件末尾添加module.exports表达式

module.exports = ChatRoom;

注意 您可能希望使用export default ChatRoom而不是module.exports。但请注意,Babel 从 6.0 版本开始导出默认在 default 键下,而不是整个导出。有关详细信息,请参阅此问题和解答。

但这还不够。您还需要设置 Webpack 以从您的代码创建库。将以下内容添加到您的 webpack.config 中.js

output: {
    library: 'ChatRoom',
    libraryTarget: 'umd'
},

有关更多详细信息,请参阅 webpack 文档