您的位置:首页 > Web前端 > Webpack

webpack中imports-loader,exports-loader,expose-loader的区别

2017-01-20 15:56 453 查看
Webpack有几个和模块化相关的loader,
imports-loader
,
exports-loader
,
expose-loader
,比较容易混淆。今天,我们来理一理。

imports-loaders

文档介绍的是:用于向一个模块的作用域内注入变量(Can be used to inject variables into the scope of a module.),官方的文档总是言简意赅但是不太好懂。我们来举个例子。
例子完整的代码可以点这里
jqGreen.js
文件里仅一行代码

//没有模块化
$('#box').css('color','green');

index.js
文件也只有一行代码

require('./jqGreen');

我们的配置文件中,是把
index.js
作为入口文件的。

{
entry:{
index:'./src/js/index.js'
}
}

注意,我们并没有引入
jquery
。所以运行的结果是
$ is not defined


但是如果我们稍微修改一下
jqGreen
的引入方式,就能很轻松的解决这个问题。
index.js
文件

require('imports?$=jquery!./jqGreen');

当然,这个能运行之前,我们要
npm install imports-loader
一下。上面代码,把变量
$
注入进模块
jqGreen.js
。同时,我们指定了变量
$=jquery
。等于是在
jqGreen.js
文件的最顶上,加上了
var $=require('jquery')
。这样,程序就不会报
$ is not defined
的错误了。

exports-loader

exports有
导出
的意思,这让我们猜测它有从模块中导出变量的功能。实际情况大致如此。我们来看个小例子。
例子的完整代码在 这里
Hello.js
文件中仅有一个方法,直接绑定在全局变量
window
上面。

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
,所以我们才能正确的导入。

expose-loader

把一个模块导出并付给一个全局变量。文档里给了一个例子:

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模块的文件里导出到全局变量的例子,有兴趣的同学点击这里
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: