zoukankan      html  css  js  c++  java
  • webpack的externals的使用

    externals

    官网文档解释的很清楚,就是webpack可以不处理应用的某些依赖库,使用externals配置后,依旧可以在代码中通过CMD、AMD或者window/global全局的方式访问。

    怎么理解呢?我们先通过官网说的那个jquery的案例来理解。

    有时我们希望我们通过script引入的库,如用CDN的方式引入的jquery,我们在使用时,依旧用require的方式来使用,但是却不希望webpack将它又编译进文件中。

    1  <script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
    View 1 <script src="http://code.jquery.com/jquery-1.12.0.min.js"></script> 
     

    jquery的使用如下

      // 我们不想这么用
      // const $ = window.jQuery
    
      // 而是这么用
      const $ = require("jquery")
      $("#content").html("<h1>hello world</h1>")
    

      

    这时,我们便需要配置externals

    module.exports = {
        ...
        output: {
          ...
          libraryTarget: "umd"
        },
        externals: {
          jquery: "jQuery"
        },
        ...
     }

    我们可以看看编译后的文件

    ({
       0: function(...) {
           var jQuery = require(1);
           /* ... */
       },
       1: function(...) {
         // 很明显这里是把window.jQuery赋值给了module.exports
         // 因此我们便可以使用require来引入了。
         module.exports = jQuery;
       },
         /* ... */
    });
    

      

    我们自己可以写个例子,当然这个例子没什么实际意义,只是为了演示如何使用而已。

    假设我们自己有个工具库,tools.js,它并没有提供给我们UMD的那些功能,只是使用window或者global的方式把工具的对象tools暴露出来

    window.Tools = {
        add: function(num1, num2) {
          return num1 + num2
        }
      }

    接下来把它放在任何页面能够引用到的地方,例如CDN,然后用script的方式引入页面

     <script src="http://xxx/tools.min.js"></script>

    一般来说我们可能会直接就这么用了

    const res = Tools.add(1,2)

    但是既然我们是模块化开发,当然要杜绝一切全局变量了,我们要用require的方式。

     const tools = require('mathTools')
     const res = tools.add(1,2)
    

      

    这是我们再来配置一些externals即可

       module.exports = {
         ...
         output: {
           ...
           libraryTarget: "umd"
         },
         externals: {
           mathTools: "tools"
         },
         ...
       }
    

    关于externals的配置

    首先是libraryTarget的配置,我们上面的例子都是umd 
    当然它还有其他配置方式,具体就看官网文档吧,我们可以看到配置成umd便可以使用任何一种引入的方式了

  • 相关阅读:
    $(this)和this 区别
    文本溢出显示省略标记'...'的bug
    web中常用的20种字体 (share)
    Underscore.js 的模板功能
    iphone webapp如何隐藏地址栏
    制作自己博客的分享按钮
    css3动画事件—webkitAnimationEnd
    获取随机的颜色
    制作自己博客的翻译工具
    兼容IE getElementsByClassName取标签
  • 原文地址:https://www.cnblogs.com/samli15999/p/7047968.html
Copyright © 2011-2022 走看看