当前位置:   article > 正文

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

imports-loader在webpack中的坑

Webpack有几个和模块化相关的loader,imports-loader,exports-loader,expose-loader,比较容易混淆。今天,我们来理一理。

imports-loaders

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

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

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

require('./jqGreen');

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

  1. {
  2. entry:{
  3. index:'./src/js/index.js'
  4. }
  5. }

注意,我们并没有引入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');。这样引用的结果是变量helloundefined。因为我们在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

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

  1. require("expose?libraryName!./file.js");
  2. // Exposes the exports for file.js to the global context on property "libraryName".
  3. // 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模块的文件里导出到全局变量的例子,有兴趣的同学点击这里

转载于:https://www.cnblogs.com/laneyfu/p/6323087.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/997708
推荐阅读
相关标签
  

闽ICP备14008679号