我假设你说的是browserify-shim。
Shimming 用于使 commonjs 不兼容的文件可浏览。
要与 commonjs 兼容,文件必须导出某些内容。这是一个简单的 commonjs 模块:
// mystring.js
module.exports = "Hello Stackoverflow";
现在在其他文件中,您可以要求 mystring.js 并像这样使用它:
var str = require('./mystring.js');
console.log(str); // > "Hello Stackoverflow"
jQuery
>
在旧版本的 jQuery(1.11 和 2.1 之前)中没有导出任何内容。相反,jQuery 会将自己附加到 window 对象。这违背了模块化的整个概念,使您的代码依赖于存在于全局范围内的对象和值。
在更复杂的环境中,以正确的顺序加载文件可能会很棘手。特别是如果某些配置文件更改了某些全局变量,并且您的脚本应该在 window.foo 设置为“bar”但其他脚本将 window.foo 值更新为“qux”之前执行。
当我们在加载之前尝试使用 jQuery 时,我们得到一个 ReferenceError:
<!-- index.hmtl -->
<script>
var $body = $('body'); // ReferenceError: Can't find variable: $
</script>
<script src="jquery.js">
这就是browserify-shim 发挥作用的地方。
垫片
本质上browserify-shim 做了这样的事情:
// jquery-shim.js
loadScript('jquery.js') // now, window.$ contains a reference to the jQuery object
module.exports = window.$; // exports that jQuery object
window.$ = null;
现在您可以在代码中的任何位置使用 jQuery,而无需依赖它出现在全局范围内:
<!-- product-page.hmtl -->
<script> <!-- script is inlined for demo purposes only -->
var $ = require('./jquery-shim.js');
var $body = $('body'); // this works now
</script>
它是关于模块化您的项目并保持您的全局范围干净。