zoukankan      html  css  js  c++  java
  • webpack中imports-loader,exports-loader,expose-loader的区别

    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');。这样引用的结果是变量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

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

    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模块的文件里导出到全局变量的例子,有兴趣的同学点击这里

  • 相关阅读:
    ios中的几种多线程实现
    在mac下使用终端管理svn
    关于UIScrollViewDelegate协议中每个回调函数的意义及执行顺序的理解
    UIView 及其子类对象 抖动效果的实现
    ios、andriod、cocos2d 视图层次理解
    委托  通知中心   监听/观察
    iphone 中使用苹果禁用的私有Framework
    关于苹果官方网站Reachability检测网络的总结
    iOS设备的分辨率
    ios开发多线程、网络请求的理解 错误码的理解
  • 原文地址:https://www.cnblogs.com/laneyfu/p/6323087.html
Copyright © 2011-2022 走看看