教你搭建按需加载的Vue组件库

10,855

按需加载的原理

按需加载,本质上是把一个组件库的不同组件拆分成不同文件,按照需要引用对应的文件,而该文件暴露一个install方法,供Vue.use使用。 比如:我只想引用element库里的一个Button组件

import Button from 'element-ui/lib/Button.js'
import Button from 'element-ui/lib/theme-chalk/Button.css'

Vue.use(Button);

上面的写法比较繁琐,而且需要知道每个组件的实际路径,使用起来并不方便,所以我们还需要借助一个转换插件。

先来看看element是怎么做的,官方的的「快速手上」:

image

element使用一个了babel插件,作用就是代码转换:

import { Button } from 'components'

// 转换为

var button = require('components/lib/button')
require('components/lib/button/style.css')

到这我们可以知道,要搭建一个按需加载的组件库。主要工作需要两点:

  1. 组件独立打包,单个文件对应单个组件
  2. 引入代码转换的插件

组件代码的编写规范

我们在项目的跟目录建一个文件夹packages,下面放我们的组件:

image

packages下每一个文件夹对应一个组件所需要的资源,在index.js定义组件的install方法。而packages/index.js存放了在全量加载时用的install方法

packages/Button/index.js:
import Button from './src/main';

Button.install = function(Vue) {
  Vue.component(Button.name, Button);
};

export default Button;
packages/Button/src/main.vue:
<template>
  <div>
    我是一个Button组件
  </div>
</template>

packages/index.js:
import Button from './Button';
import Loading from './Loading';
import LoadMore from './LoadMore';

const components = [
  Button,
  LoadMore,
  Loading
];

const install = function(Vue) {
  components.forEach(component => {
    Vue.component(component.name, component);
  });
}

if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue)
}

export default {
  install, // 全量引入
  Button,
  LoadMore,
  Loading
};

webpack配置

组件代码写好了,接下来需要配置一下webpack的打包逻辑。我们复用vue-cli生成的模板,在上面做一些必要更改:

多入口

每个组件独立生成一个对应的js和css,这就需要我们在入口处就把组件的引用定义好:

webpack.prod.conf.js:
const entrys = {
    Button: path.resolve(__dirname, '../packages/Button'),
    index: path.resolve(__dirname, '../packages')
};

const webpackConfig = merge(baseWebpackConfig, {
  entry: entrys,
  // ......
});

上述配置每增加一个组件都需要修改entrys,我们可以优化一下,使其动态生成

webpack.prod.conf.js:
const entrys = require(./getComponents.js)([组件目录入口]);
const webpackConfig = merge(baseWebpackConfig, {
  entry: entrys,
  ......
});
getComponents.js:
const fs = require('fs');
const path = require('path');

/**
 * 判断刚路径是否含有index.js
 * @param {String} dir 
 */
function hasIndexJs(dir) {
    let dirs = [];
    try {
        dirs = fs.readdirSync(dir);
    } catch(e) {
        dirs = null;
    }
    return dirs && dirs.includes('index.js');
}

/**
 * 获取指定入口和入口下包含index.js的文件夹的路径
 * @param {String} entryDir 
 */
const getPath = function(entryDir) {
    let dirs = fs.readdirSync(entryDir);
    
    const result = {
        index: entryDir
    };
    dirs = dirs.filter(dir => {
        return hasIndexJs(path.resolve(entryDir, dir));
    }).forEach(dir => {
        result[dir] = path.resolve(entryDir, dir); 
    });
    return result;
}

module.exports = getPath;
修改webpack的输出

默认生成的js文件并不支持ES6引入,在这里我们设置成umd

output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('[name].js'),
    library: 'LoadOnDemand',
    libraryTarget: 'umd'
},

配置 babel-plugin-component -D

上面的组件库打包发布到npm上之后。我们在使用的时候npm install babel-plugin-component -D之后,修改一下.babelrc.js:

"plugins": [
    [
      "component",
      {
        "libraryName": "load-on-demand", // 组件库的名字
        "camel2Dash": false, // 是否把驼峰转换成xx-xx的写法
        "styleLibrary": {
          "base": false, // 是否每个组件都默认引用base.css
          "name": "theme" // css目录的名字
        }
      }
    ]
  ],

这里提一下属性camel2Dash,默认是开启的,开启状态下假如你的组件名是vueCompoent,引用的css文件会变成vue-component.css。

结语

上面demo的代码放在了个人github github.com/jmx16449196… 大家如果有更好的实现方法,或者我上面还有什么需要更正的错误,欢迎交流。

更多前端技术分享请订阅微信公众号“前端技术干货分享圈”