简体   繁体   English

browserify在全局和模块中使用JQuery

[英]browserify Using JQuery globally and in Module

I have been given a template to work from by a client that has some 28 different jquery plugins that the client wants to use (eg ditching them not an option). 我得到了一个模板,由一个客户端工作,该客户端有28个不同的jquery插件,客户端想要使用它们(例如,放弃它们不是一个选项)。

However I really want to use browserify to modularise my code, but short of trying to shim all 28 plugin and thir dependancy I can't work out how I would do that and not have to load JQuery for browserify and globally. 但是我真的想使用browserify来模块化我的代码,但是没有尝试去填充所有28个插件和他们的依赖性,我无法弄清楚我将如何做到这一点而不必为浏览器和全局加载JQuery。

I tried doing this: 我试过这样做:

window.JQuery = require('jquery')
window.$ = window.JQuery

And this: 还有这个:

var globals = function(){
  window.JQuery = require('jquery')
  window.$ = window.JQuery
}

globals();

But neither seem to work and all the plugins throw an error. 但似乎都没有工作,所有的插件都会抛出错误。 Does anyone now how I might make it work? 现在有人如何让它发挥作用?

This is a pretty good way to do it, I think. 我认为这是一个非常好的方法。

  1. npm install jquery npm install jquery
  2. npm install browserify-shim npm install browserify-shim
  3. Put this line in your package.json: 把这一行放在你的package.json中:

     browserify-shim" : { "./node_modules/jquery/dist/jquery.js" : "$" } 

So on the server, your usual require('jquery') will point to the node_modules spot. 所以在服务器上,你通常的require('jquery')将指向node_modules点。 When you run browserify, it will set window.$ to the same code (you could also use jQuery ). 当你运行browserify时,它会将window.$设置为相同的代码(你也可以使用jQuery )。 Also, if you did want to shim those plugins, just add them like this: 此外,如果您确实想要填充这些插件,只需像这样添加它们:

    "browserify-shim" : {
      "./node_modules/jquery/dist/jquery.js" : "jQuery",
      "./plugins/bs_modal.js" :  { 
        "depends": [ "./node_modules/jquery/dist/jquery.js" ] 
      }
    }

or, cleaner: 或者,清洁:

    "browser" : {"jquery": "./node_modules/jquery/dist/jquery.js"},
    "browserify-shim" : {
      "jquery" : "jQuery",
      "./plugins/bs_modal.js" :  { 
        "depends": [ "jquery" ] 
      }
    }

我一直在使用下面的行,以获得浏览器的bootstrap和jquery:

window.$ = window.jQuery = require('jquery');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM