webpack之打造Javascript类库

最近有个需求,需要将组件库打包为类库,提供给各项目使用,并且不打包进项目中,优化各项目切换时的资源加载,但是又不想影响我们在程序中的写法(以import方式引用使用)。

webpack的externals配置提供了这种方法。

externals

防止将某些 import 的包(package)打包到 bundle 中,而是在运行时(runtime)再去从外部获取这些扩展依赖(external dependencies)

例如,从 CDN 引入 jQuery,而不是把它打包:

index.html

<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'
    }
};

这样就剥离了那些不需要改动的依赖模块,换句话,下面展示的代码还可以正常运行:

import $ from 'jquery';
$('.my-element').animate(/* ... */);

具有外部依赖(external dependency)的 bundle 可以在各种模块上下文(module context)中使用。

因此,我们找到了如何使用我们自己的类库的方法,将该配置加入要使用的项目中,并在html中添加自己的类库的脚本即可(myLibrary是我们接下来将要导出的类库全局变量名)

webpack.config.js

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 下的变量。

猜你喜欢

转载自blog.csdn.net/weixin_34318272/article/details/86900262