最近有个需求,须要将组件库打包为类库,提供给各项目使用,而且不打包进项目中,优化各项目切换时的资源加载,可是又不想影响咱们在程序中的写法(以import方式引用使用)。html
webpack的externals配置提供了这种方法。jquery
防止将某些 import 的包(package)打包到 bundle 中,而是在运行时(runtime)再去从外部获取这些扩展依赖(external dependencies)。webpack
例如,从 CDN 引入 jQuery,而不是把它打包:web
index.htmlbash
<script src="https://code.jquery.com/jquery-3.1.0.js" integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk=" crossorigin="anonymous"></script>
复制代码
webpack.config.js优化
module.exports={
//...
externals: {
jquery:'jQuery'
}
};
复制代码
这样就剥离了那些不须要改动的依赖模块,换句话,下面展现的代码还能够正常运行:spa
import $ from 'jquery';
$('.my-element').animate(/* ... */);
复制代码
具备外部依赖(external dependency)的 bundle 能够在各类模块上下文(module context)中使用。code
所以,咱们找到了如何使用咱们本身的类库的方法,将该配置加入要使用的项目中,并在html中添加本身的类库的脚本便可(myLibrary是咱们接下来将要导出的类库全局变量名)htm
webpack.config.jsip
module.exports={
//...
externals: {
'my-library': 'myLibrary'
}
};
复制代码
那么一切都准备好了,接下来咱们应该怎么将咱们的组件库打包成类库呢? 咱们将下面这段配置加入要打包的本身的类库中:
webpack.config.js
module.exports = {
//...
output: {
library: 'myLibrary',
libraryTarget: 'umd'
}
};
复制代码
在这个例子中,你须要 library 属性来命名你的模块。 library: 定义类库的全局变量名,当经过 script 脚本引入时使用 libraryTarget: "umd" - 为了使你的类库更通用,这里选择使用umd,将你的 library 暴露为全部的模块定义下均可运行的方式。它将在 CommonJS, AMD 环境下运行,或将模块导出到 global 下的变量。