Creating a bundle supporting browserify and jQuery <script> tag loading

余生颓废 提交于 2020-01-23 06:28:38

问题


I am working on a JavaScript library (bitcoin-prices.js) which I'd like to maintain using browserify. The library depends on jQuery. I would not like to force the library users move to browserify, but retain "drop one file + script tag" integration for those who have not drank the latest koolaid from JavaScript community.

My question is how to create a bundle.js with browserify, so that

  • browserify-enabled users can install the package from NPM, having proper jQuery dependency

  • Traditional users can as still use <script> tag drop in bundle, loading their jQuery wherever they want to with another <script> and the code still works fine

I guess some kind of boilerplate code is needed around $ = require('jquery.js')?


回答1:


The convention is to do like this (without the .js):

var $ = require('jquery')

If you are using grunt-browserify (https://github.com/jmreidy/grunt-browserify),

Compile your library in this way:

  your_task:{
    src:'{{your library's js file}}',
    dest:'{{your library's browserified file}}',
    options: {
      external: ["jquery"]
    }
  },

At the home page, the sequence will then be like this:

<header>
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
      <script type="text/javascript" src="{{your library's browserified file}}"></script>
</header>

Hope this helps



来源:https://stackoverflow.com/questions/20915307/creating-a-bundle-supporting-browserify-and-jquery-script-tag-loading

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