我正在尝试使用 es6 制作聊天室连接类。我正在使用rabbitmq/STOMP 将交换数据推送给订阅者。我使用的代码以 es5 风格运行,但我对交换名称进行了硬编码。我正在使用 webpack/babel 将此代码转译回 es5 中的一个名为 chat.bundle.js
的文件,但是当我运行时:
var chatRoom = new ChatRoom('thisExchange');
控制台日志:Uncaught ReferenceError:ChatRoom 未定义
我在加载 bundle 文件后实例化类 ChatRoom
(在 bundle 的脚本标记下方)。
我知道 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 文件的语法,如上所示。
最佳答案
通常,模块 bundler (例如 webpack)不会公开模块局部变量。
如果要将类 ChatRoom
导出为公共(public) API,请在文件末尾添加 module.exports
表达式
module.exports = ChatRoom;
NB You may want to use
export default ChatRoom
instead ofmodule.exports
. But be aware that Babel since 6.0 version exports default under thedefault
key rather than entire export. See this question and answers for more information.
但这还不够。您还需要设置 Webpack 以从代码创建库。将以下内容添加到您的 webpack.config.js
output: {
library: 'ChatRoom',
libraryTarget: 'umd'
},
参见webpack docs了解更多详情
关于javascript - 实例化一个 es6 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35368210/