Webpack有几个和模块化相关的loader,imports-loader
,exports-loader
,expose-loader
,比较容易混淆。今天,咱们来理一理。javascript
文档介绍的是:用于向一个模块的做用域内注入变量(Can be used to inject variables into the scope of a module.),官方的文档老是言简意赅可是不太好懂。咱们来举个例子。
例子完整的代码能够点这里jqGreen.js
文件里仅一行代码css
//没有模块化 $('#box').css('color','green');
index.js
文件也只有一行代码java
require('./jqGreen');
咱们的配置文件中,是把index.js
做为入口文件的。jquery
{ entry:{ index:'./src/js/index.js' } }
注意,咱们并无引入jquery
。因此运行的结果是$ is not defined
。webpack
可是若是咱们稍微修改一下jqGreen
的引入方式,就能很轻松的解决这个问题。index.js
文件git
require('imports?$=jquery!./jqGreen');
固然,这个能运行以前,咱们要npm install imports-loader
一下。上面代码,把变量$
注入进模块jqGreen.js
。同时,咱们指定了变量$=jquery
。等因而在jqGreen.js
文件的最顶上,加上了var $=require('jquery')
。这样,程序就不会报$ is not defined
的错误了。github
exports有导出
的意思,这让咱们猜想它有从模块中导出变量的功能。实际状况大体如此。咱们来看个小例子。
例子的完整代码在 这里Hello.js
文件中仅有一个方法,直接绑定在全局变量window
上面。web
window.Hello = function(){ console.log('say hello.'); }
而后咱们在index.js
文件里去引用这个Hello.js
:var hello = require('./Hello.js');
。这样引用的结果是变量hello
是undefined
。由于咱们在Hello.js
文件里没有写module.exports=window.Hello
,因此index.js
里咱们require
的结果就是undefined
。这个时候,exports-loader
就派上用场了。咱们只用把index.js
的代码稍微改动一下:var hello = require('exports?window.Hello!./Hello.js');
,这个时候,代码就能正确的运行了。变量hello
就是咱们定义的window.hello
啦。var hello = require('exports?window.Hello!./Hello.js');
这行代码,等于在Hello.js
里加上一句module.exports=window.Hello
,因此咱们才能正确的导入。npm
把一个模块导出并付给一个全局变量。文档里给了一个例子:浏览器
require("expose?libraryName!./file.js"); // Exposes the exports for file.js to the global context on property "libraryName". // In web browsers, window.libraryName is then available.
例子中的注释是说把file.js中exports出来的变量付给全局变量"libraryName"
。假如file.js
中有代码module.exports=1
,那么require("expose?libraryName!./file.js")
后window.libraryName
的值就为1(咱们这里只讨论浏览器环境)。
我这里还有一个稍稍复杂点的从一个umd模块的文件里导出到全局变量的例子,有兴趣的同窗点击这里。