将Vue组件库更换为按需加载的方法步骤

2020-06-16 06:44:51易采站长站整理

将组件导出分为两种类型。基础组件,按需引入组件。
按需引入组件的评定标准为:

较少业务系统使用
组件中包含体积较大或资源文件较多的第三方依赖
未被其他组件内部引用

全量导出模式导出全部组件,基础导出仅导出基础组件。在需要使用按需引入组件时,需要自行引入对应组件。

调整为按需引入

参考 element-ui 的导出方案,组件库导出的组件依赖,要提供每个组件单独打包的依赖文件。

全量导出 index.js 文件无需改动,在 index.js 同级目录增加新文件 base.js,用于导出基础组件。

base.js


import Button from "./Button";
import Table from "./table";

const components = {
Button,
Table
}

const install = (Vue) => {
Object.keys(components).forEach(component => Vue.use(component));
}

export default {
install,
...components
}

修改组件库脚手架工具,增加额外打包配置。用于编译组件文件,输出编译后的依赖。

vue.config.js


const devConfig = require('./build/config.dev');
const buildConfig = require('./build/config.build');

module.exports = process.env.NODE_ENV === 'development' ? devConfig : buildConfig;

config.build.js


const fs = require('fs');
const path = require('path');
const join = path.join;
// 获取基于当前路径的目标文件
const resolve = (dir) => path.join(__dirname, '../', dir);

/**
* @desc 大写转横杠
* @param {*} str
*/
function upperCasetoLine(str) {
let temp = str.replace(/[A-Z]/g, function (match) {
return "-" + match.toLowerCase();
});
if (temp.slice(0, 1) === '-') {
temp = temp.slice(1);
}
return temp;
}

/**
* @desc 获取组件入口
* @param {String} path
*/
function getComponentEntries(path) {
let files = fs.readdirSync(resolve(path));

const componentEntries = files.reduce((fileObj, item) => {
// 文件路径
const itemPath = join(path, item);
// 在文件夹中
const isDir = fs.statSync(itemPath).isDirectory();
const [name, suffix] = item.split('.');

// 文件中的入口文件
if (isDir) {
fileObj[upperCasetoLine(item)] = resolve(join(itemPath, 'index.js'))
}
// 文件夹外的入口文件
else if (suffix === "js") {
fileObj[name] = resolve(`${itemPath}`);
}
return fileObj
}, {});

return componentEntries;
}

const buildConfig = {
// 输出文件目录
outputDir: resolve('lib'),