2016-02-12 116 views
1

我正在嘗試使用es6來創建聊天室連接類。我正在使用rabbitmq/STOMP將交換數據推送給訂戶。我使用的代碼已經以es5風格工作,但我對交換名稱進行了硬編碼。我使用的WebPack /通天transpile該代碼回來叫chat.bundle.js文件ES5但是當我運行:實例化es6類

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('[email protected]');</script> 

的WebPack成功建立,不抱怨的語法聊天包的es6文件如上所示。

+0

webpack docs這可能是因爲你的類從未定義。你在「使用嚴格」模式?如果不是這樣,可能與下面的帖子有相同的答案: http://stackoverflow.com/questions/34231445/es6-classes-dont-work-on-chrome-47 –

+0

一些提示:是chat.bundle。 js文件正確創建(沒有任何錯誤)?你什麼時候做'var chatRoom = new ChatRoom('thisExchange');'?檢查你在哪裏訪問'輸出' – topheman

+0

我在HTML文件中添加了更多行,其中包含腳本標籤。在捆綁文件中似乎沒有任何錯誤 – kinghenry14

回答

1

通常,模塊打包程序(如webpack)不會公開模塊本地文件。 如果你想你的ChatRoom類導出爲公共API,在您的文件

module.exports = ChatRoom; 

的末尾添加module.exports表達NB您可能需要使用export default ChatRoom,而不是module.exports。但請注意,從6.0版本開始,Babel導出默認值爲default,而不是整個導出。有關更多信息,請參閱this question and answers

但這還不夠。您還需要安裝Webpack以從您的代碼創建一個庫。添加以下到您的webpack.config.js

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

更多細節