Webpack的externals的使用

通过这种方式引入的依赖库,不需要webpack处理,编译进文件中,在我们需要,使用它的时候可以通过CMD、AMD、或者window全局方式访问。

 
比如我们在index.html用CDN的方式引入jquery,webpack编译打包时不处理它,却可以引用到它。

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

使用

const $ = require("jquery")
$("#content").html("<h1>hello world</h1>")
配置

externals: {
      jquery: "jQuery"
    },
 

其实,我们使用这种方式的另一个目的是为了压缩工程大小,如果所有的依赖包都压缩打包到应用中,尤其是echart这样的大型库,会导致文件过大,如果外部引入,按需引入,可以压缩应用大小。

我们可以自己写一个例子,引入到工程中

定义一个tools.js文件
编写一个方法

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


    3.在index.html中引入它(先放到CDN中)

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


    4.配置externals

externals: {
mathTools: "tools"
},


  5.使用

const tools = require('mathTools')

const res = tools.add(1,2)
      或者

Import tools = from 'mathTools'

var res = tools.add(1,2)

Console.log(res)

猜你喜欢

转载自www.cnblogs.com/plBlog/p/12175701.html