背景:重复的代码

通过简单的配置,已经能够将 es6 转化成 es5 了,但是这边还存在一个问题,如下:
我们在原有的文件基础上,再引入另外一个 es6 文件。

  1. /** ./src/a.js **/
  2. class A {
  3. getType(){
  4. console.log('A class')
  5. }
  6. }
  7. export default A;
  1. /** ./src/index.js **/
  2. import A from './a';
  3. class Animal {
  4. constructor(type){
  5. this.type = type;
  6. }
  7. getType(){
  8. return this.type;
  9. }
  10. }
  11. const pig = new Animal('猪');
  12. console.log(pig.type);

这时我们在进行打包。结果如下:
image.png
比较一下我用红框框出来的函数 _classCallCheck、_createClass,你会发现它们都是一样的,所以这些代码都重复了,实际上我们可以把这些代码提取出来作为公共函数,如何实现如下:

提取公共函数

提取公共函数需要用到两个 npm 包,@babel/plugin-transform-runtime 和 @babel/runtime。

  • @babel/runtime 是运行时依赖
  • @babel/plugin-transform-runtime 是开发时依赖,这个包依赖@babel/runtime。

    安装

    ```shell //这边注意: //@babel/plugin-transform-runtime 是开发时依赖 //@babel/runtime 是运行时依赖

yarn add @babel/plugin-transform-runtime —dev yarn add @babel/runtime

  1. <a name="zHZSL"></a>
  2. ### webpack 配置
  3. 只需要在 loader 的 options 配置 plugins 就行。
  4. ```javascript
  5. /** ./webpack.config.js **/
  6. //...
  7. let path = require('path');
  8. module.exports = {
  9. //..
  10. modules:{
  11. rules: [
  12. //..
  13. {
  14. test: /\.js$/,
  15. exclude: /node_modules/,
  16. include: path.resolve(__dirname, './src'),
  17. use:[
  18. {
  19. loader: 'babel-loader',
  20. options: {
  21. presets: ['@babel/preset-env'],
  22. plugins: ['@babel/plugin-transform-runtime']
  23. }
  24. }
  25. ]
  26. }
  27. //..
  28. ]
  29. }
  30. //..
  31. }

打包结果

最后我们再看打包后的公共函数,如下:
image.png
我们发现 _classCallCheck、_createClass 函数都被单独的抽离了出来,分别在 a.js 和 index.js 中使用,如下:
image.png