Reputation: 1185
I am trying to use es6 to make a chatroom connection class. I am using rabbitmq/STOMP to push the exchange data to subscribers. The code I am using had worked in es5 style, but I was hardcoding the exchange name. I am using webpack/babel to transpile this code back to es5 in a file called chat.bundle.js
but when I run:
var chatRoom = new ChatRoom('thisExchange');
The console logs: Uncaught ReferenceError: ChatRoom is not defined
I am instantiating the class ChatRoom
after the bundle file is loaded (below this script tag for the bundle).
I know probably the load()
function will not work... I am new to es6 classes and not sure how to get window.load to work but this is a separate issue. For now I just want to be able to instantiate this class by providing the argument of the exchangeName
and then move on to new errors after this.
Here is my terribly written es6 class:
// 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
);
}
});
}
}
In my html file, the script tags are structured as follow:
<script src="static/chat.bundle.js"></script>
<script>var chatRoom=new ChatRoom('soccer@newark');</script>
Webpack builds successfully and does not complain about the syntax of the es6 file for the chat bundle as shown above.
Upvotes: 0
Views: 1231
Reputation: 9746
Usually, module bundlers such as webpack don't expose module locals.
If you want to export your class ChatRoom
as public API, add module.exports
expression at the end of your file
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.
But this is not enough. You also need setup Webpack to create a library from your code. Add the following into your webpack.config.js
output: {
library: 'ChatRoom',
libraryTarget: 'umd'
},
See webpack docs for more details
Upvotes: 1