如何解决browserify(基于Backbone的应用程序)与同一页面上的require.js之间的冲突? [英] How to solve a conflict between browserify (Backbone based app) and require.js on the same page?

查看:95
本文介绍了如何解决browserify(基于Backbone的应用程序)与同一页面上的require.js之间的冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个骨干应用程序并正常运行.它打算在第3页中用作小部件.不幸的是,我只是意识到其中一个页面已经加载了Backbone/下划线.

I have a backbone app up and running correctly. It's meant to be used as a widget in 3rd pages. Unfortunately, I just realised that one of these pages has already Backbone / underscore loaded.

我收到这样的错误:

Uncaught TypeError: Cannot read property 'extend' of undefined 

通常在未预先加载下划线的情况下显示.

Which usually appear when underscore has not been previously loaded.

我的典型视图是这样的:(正常的主干视图)

My typical view is like this: (normal Backbone view)

./view1.js

./view1.js

var Backbone = require('backbone')
var _ = require('underscore')
var $ = require('jquery')
Backbone.$ = $

module.exports = Backbone.View.extend({

  events: {

  },

  initialize: function () {

  },

  render: function () {

  }
})

那我只需要叫它:

var View1 = require('view1')
var view1Instance = new View1(...)

感谢您的帮助:)

调查后 通过调试器运行时,似乎Backbone变量是一个空对象,而不是Backbone.好像require('backbone')刚返回了{}

EDIT after investigation: When running through the debugger, it appears that the Backbone variable is an empty object instead of being Backbone. As if the require('backbone') just returned {}

似乎与此问题有关: https://github.com/substack/node-browserify/Issues/790

It seems related to this issue: https://github.com/substack/node-browserify/issues/790

推荐答案

Backbone和Requirejs(所示的问题在这里thlorenz )

The problem with Backbone and Requirejs (as indicated by thlorenz here)

  • 主干先查找define,然后再查找module.exports
  • requirejs与全局变量一起使用不是很好的做法,在这种情况下会引起问题,因为它会影响以相同方式运行的所有内容 浏览器标签
  • backbone looks for define before looking for module.exports
  • requirejs works with globals which is not good practice and in this case causes problems since it affects everything that runs in the same browser tab

他建议将所有内容包装在一个作用域中,并隐藏define函数. 他还有一个工具可以做到这一点. browserify-shim

He advises to wrap everything in a scope and hide the define function. He has also a tool to do that.browserify-shim

但是我没有使用它,而是Browserify的postBundleCB选项:(谢谢同事).

However I did not use that but the postBundleCB option from Browserify: (thx to a coworker).

在我的Gruntfile中:

browserify: {
  dist: {
    src: ['src/app/app.js'],
    dest: 'www/app.js',
    options: {
      postBundleCB: function (err, src, next) {
        return next(null, '(function () { var define = undefined; '+src+' })();')
      }
    }
  }
},

这解决了我的问题:)

我没有尝试过browserify-shim,所以对此我不太了解.

I didn't try browserify-shim, so I don't know much about it.

这篇关于如何解决browserify(基于Backbone的应用程序)与同一页面上的require.js之间的冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆