问题描述
我正在尝试慢慢地将Browserify引入我的网站,但我不想重写所有的js,我不希望重复的jquery实例和我的Browserify构建捆绑的其他库。
I am trying to slowly introduce Browserify into my site, but I don't want to rewrite all the js and I don't want duplicate instances of jquery and other libraries bundled with my Browserify build.
如果我构建我的模块列出jquery作为外部依赖项,那么我如何将它指向我的全局jquery实例?另外目标是消除mylibs全局(例如下面的例子),所以我不想在我的模块中使用它。
If I build my module listing jquery as an external dependency, how do I then point it at my global jquery instance? Also the goal is to eliminate the mylibs global (example below), so I don't want to use it in my module.
这就是我想要的做(psudo-code)。这将是我网站的回购 - 而不是模块的回购。该模块将与Bower一起安装:
This is what I'm trying to do (psudo-code). This would be in my site's repo - not the module's. The module would be installed with Bower:
var mylibs.jQuery = $.noConflict(); // global used by lots of existing code
module.exports = {
jquery: mylibs.jQuery // can be imported by my module as require('jquery')
};
这就是我想要实现的目标。这可能吗?
Something like that is what I'm trying to achieve. Is this possible?
推荐答案
你可以通过。假设您有一个名为 mymodule.js
的模块,该模块依赖于全局范围内的jQuery,其中包含以下内容:
You can achieve that by using browserify-shim. Assuming that you've got a module named mymodule.js
that depends on jQuery in the global scope with the following contents:
var $ = require('jQuery');
console.log(typeof $);
-
安装browserify-shim:
Install browserify-shim:
npm install browserify-shim --save-dev
在package.json文件中,告诉browserify使用browserify-shim作为转换:
In package.json file, tell browserify to use browserify-shim as a transform:
{
"browserify": {
"transform": [ "browserify-shim" ]
}
}
在package.json文件中,告诉browserify-shim将jQuery映射到全局范围内的jQuery:
In package.json file, tell browserify-shim to map jQuery to the jQuery in the global scope:
{
"browserify-shim": {
"jQuery": "global:jQuery"
}
}
运行browserify
Run browserify
browserify mymodule.js > bundle.js
如果你检查bundle.js你会注意到 require('jQuery')
被替换为(window.jQuery)
。
If you examine bundle.js you will notice that require('jQuery')
is replaced with (window.jQuery)
.
这篇关于如何将Browserify与外部依赖项一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!