【问题标题】:instantiating an es6 class实例化一个 es6 类
【发布时间】:2016-02-12 16:59:14
【问题描述】:

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

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 文件的语法。

【问题讨论】:

  • 可能是您的类从未定义过。您是否处于“使用严格”模式?如果不是,这可能与以下帖子的答案相同:stackoverflow.com/questions/34231445/…
  • 一些提示:chat.bundle.js 文件是否正确创建(没有任何错误)?你什么时候做var chatRoom = new ChatRoom('thisExchange');?检查您访问output的地点和时间
  • 我在包含脚本标签的 HTML 文件中添加了几行。捆绑文件中似乎没有任何错误

标签: javascript ecmascript-6 babeljs


【解决方案1】:

通常,诸如 webpack 之类的模块打包器不会暴露模块本地变量。 如果您想将您的类ChatRoom 导出为公共API,请在文件末尾添加module.exports 表达式

module.exports = ChatRoom;

NB您可能想要使用export default ChatRoom 而不是module.exports。但请注意,Babel 从 6.0 版本开始默认导出 default 键而不是整个导出。请参阅this question and answers 了解更多信息。

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

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

详情请见webpack docs

【讨论】:

    猜你喜欢
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 2015-12-09
    • 2021-10-13
    • 1970-01-01
    相关资源
    最近更新 更多