通過這種方式引入的依賴庫,不需要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)