让marionette.backbone与webpack hot module replacement

时间:2016-01-24 16:14:41

标签: backbone.js webpack webpack-dev-server webpack-hmr

我使用了来自here的示例项目来设置一个更换热模块的webpack项目。然后我建立了一个示例骨干应用程序。

// main.js
import $ from 'jquery';
import Backbone from 'backbone';

import Router from './router';

window.app = window.app || {};

const app = new Backbone.Marionette.Application();
app.addRegions({content: '#content'});

app.on('start', () => {
    if (Backbone.history)
      Backbone.history.start({ pushState: true })
}

);

app.addInitializer(() => {
  return new Router();
});


$( () => { app.start() });

// HMR
if (module.hot) {
    module.hot.accept();
}

我可以看到HRM根据[HMR] connected调试输出正常加载。 当文件发生变化时,我可以看到它根据以下输出重建并推送更新到客户端:

[HMR] Updated modules:
process-update.js?e13e:77 [HMR]  - ./app/backbone/views/template.hbs
process-update.js?e13e:77 [HMR]  - ./app/backbone/views/hello.js
process-update.js?e13e:77 [HMR]  - ./app/backbone/router.js

然而,屏幕没有重新加载。没有任何事情发生。

知道如何让它发挥作用吗?或HMR应该只与React一起使用?

1 个答案:

答案 0 :(得分:5)

它有点诡计,但你可以让它与骨干一起工作。博文是here that explains it fairly well。 (免责声明,我写了)

简而言之,您需要明确告诉您的父视图您可以接受热重新加载,然后重新require新的热重新加载视图,关闭现有的子视图,然后重新呈现它。以下示例使用Ampersand,但相同的基本原则适用于Marionette或vanilla Backbone

/* parent.view.js */
var ChildView = require('./child.view.js');
var ParentView = AmpersandView.extend({
    template : require('path/to/template.hbs')

    initialize: function(){
        var self = this;
        if(module.hot){
            module.hot.accept('./child.view.js', function(){
                // re-require your child view, this will give you the new hot-reloaded child view
                var NewChildView = require('./child.view.js');
                // Remove the old view.  In ampersand you just call 'remove'
                self.renderChildView(NewChildView);
            });
        }
    },

    renderChildView(View){
        if(this.child){
            this.child.remove();
        }
        // use passed in view
        var childView = new View({
            model: this.model
        });
        this.child = this.renderSubview(childView, this.query('.container'));
    } 

    render: function(){
        this.renderWithTemplate(this);
        renderChildView(ChildView);
        return this;
    }
});

```