How to use browserify to bundle a backbone app?

心不动则不痛 提交于 2019-11-28 21:34:36

Edit:

The most recent version of jquery is distributed and usable via npm! This makes using jquery with browserify simpler.

All we need to do now is install the packages:

npm install jquery backbone

And require the modules:

var $ = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;

Old answer:

I've used the jquery-browserify module successfully for this.

Run npm install jquery-browserify backbone

Creating a view module in a file named app-view.js:

var Backbone = require('backbone');
var $ = require('jquery-browserify');
Backbone.$ = $;

module.exports = Backbone.View.extend({
  initialize: function(){
    this.render();
  },

  render: function(){
    console.log('wuuut')
    $('body').prepend('<p>wooooooooooooooo</p>');
  }
});

Using the module:

var AppView = require('./app-view')

var appView = new AppView();

You can keep jquery in a script tag like in your code rather than using jquery-browserify, but in that case instead of this:

var $ = require('jquery-browserify');
Backbone.$ = $;

I would do this:

var $ = Backbone.$ = window.$;

Since jQuery v2, it is capable of exposing itself as module.exports. That is, you can install the jquery module instead of something like jquery-browserify.

npm install jquery backbone

But it is still necessary to correct Backbones $ property manually.

var backbone = require('backbone')
backbone.$ = require('jquery')

It is a 100% percent jQuery issue. The error is: Cannot read property 'Deferred' of undefined. Where Deferred is supposed to be? In jQuery (http://api.jquery.com/jQuery.Deferred/). Here it is a specific line, that causes an error: https://github.com/jeromegn/Backbone.localStorage/blob/master/backbone.localStorage.js#L145. Just do Backbone.$ = window.$ when you require backbone for the first time and it will work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!