2023.2 ElementUI源码-学习npm run dev
本文是为了学习组件库搭建思路而衍生的一篇文章,最近在思考搭建项目业务组件库,发现公司封装的命令也是基于
vue2
的,因此开始了学习ElementUI
源码学习之路。从
npm run dev
开始
为什么执行npm run dev得时候要执行npm run build:file这一步
"dev": "npm run bootstrap && npm run build:file && cross-env NODE_ENV=development webpack-dev-server --config build/webpack.demo.js & node build/bin/template.js",
npm run bootstrap
即执行的->"bootstrap": "yarn || npm i",
这一步很简单就是运行前执行npm i
下载依赖项,后面的npm run build:file
是打包一系列文件用的,为什么要将这些文件打包呢?先来看下
npm run build:file
做了哪些事情吧
"build:file": "node build/bin/iconInit.js & node build/bin/build-entry.js & node build/bin/i18n.js & node build/bin/version.js",
可以看到是对icon
、entry
,i18n
,version
等进行打包
build icon
node build/bin/iconInit.js
postcss.parse
方法返回一个新的根或者一个文档节点
postcss.parse.nodes
将css节点以js数组的方式输出
'use strict';
var postcss = require('postcss');
var fs = require('fs');
var path = require('path');
//加载Icon文件
var fontFile = fs.readFileSync(path.resolve(__dirname, '../../packages/theme-chalk/src/icon.scss'), 'utf8');
var nodes = postcss.parse(fontFile).nodes;
var classList = [];
//遍历所有Node,截取css类的类名最终classList中存的内容
//例如:读取到的.el-icon-ice-cream-round:before ,处理后的class ice-cream-round
nodes.forEach((node) => {
var selector = node.selector || '';
var reg = new RegExp(/\.el-icon-([^:]+):before/);
var arr = selector.match(reg);
if (arr && arr[1]) {
classList.push(arr[1]);
}
});
//为什么要倒序不明白?可能组件库的icon也不是一次性就决定列入这些icon的,是逐步加进去的,每次追加icon是在文件头加的,不是追加,因此希望按照加入的顺序排列。看了下官网倒叙顺序和展示的顺序默认是一致的。
classList.reverse(); // 希望按 css 文件顺序倒序排列
//将classList的内容写入到examples\icon.json目录
fs.writeFile(path.resolve(__dirname, '../../examples/icon.json'), JSON.stringify(classList), () => {});
build entry
node build/bin/build-entry.js
为什么要用installTemplate
和listTemplate
两个数组来存组件信息?
installTemplate
单纯的组件,包含Vue.component
注册的组件;listTemplate
所有的组件,包含通知类型的组件
//components.json组件路径映射{"pagination": "./packages/pagination/index.js",}
var Components = require('../../components.json');
var fs = require('fs');
//字符串模板生成器,使用render中的传参做字符串替换
var render = require('json-templater/string');
var uppercamelcase = require('uppercamelcase');
var path = require('path');
var endOfLine = require('os').EOL;
//输出路径:src\index.js
var OUTPUT_PATH = path.join(__dirname, '../../src/index.js');
//指定引入文件路径:import Pagination from '../packages/pagination/index.js';
var IMPORT_TEMPLATE = 'import {{name}} from \'../packages/{{package}}/index.js\';';
//模板字符串进行匹配,用来生成组件安装文件
var INSTALL_COMPONENT_TEMPLATE = ' {{name}}';
//生成目标文件模板
var MAIN_TEMPLATE = `/* Automatically generated by './build/bin/build-entry.js' */
{{include}}
import locale from 'element-ui/src/locale';
import CollapseTransition from 'element-ui/src/transitions/collapse-transition';
const components = [
{{install}},
CollapseTransition
];
const install = function(Vue, opts = {}) {
locale.use(opts.locale);
locale.i18n(opts.i18n);
components.forEach(component => {
Vue.component(component.name, component);
});
Vue.use(InfiniteScroll);
Vue.use(Loading.directive);
Vue.prototype.$ELEMENT = {
size: opts.size || '',
zIndex: opts.zIndex || 2000
};
Vue.prototype.$loading = Loading.service;
Vue.prototype.$msgbox = MessageBox;
Vue.prototype.$alert = MessageBox.alert;
Vue.prototype.$confirm = MessageBox.confirm;
Vue.prototype.$prompt = MessageBox.prompt;
Vue.prototype.$notify = Notification;
Vue.prototype.$message = Message;
};
/* istanbul ignore if */
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue);
}
export default {
version: '{{version}}',
locale: locale.use,
i18n: locale.i18n,
install,
CollapseTransition,
Loading,
{{list}}
};
`;
delete Components.font;
//所有组件的名称
var ComponentNames = Object.keys(Components);
//导入组件数组
var includeComponentTemplate = [];
//为什么要用两个数组来存?不包含'Loading', 'MessageBox', 'Notification', 'Message', 'InfiniteScroll'
var installTemplate = [];
//Loading
var listTemplate = [];
ComponentNames.forEach(name => {
//将组件名首字母变为大写
var componentName = uppercamelcase(name);
//引入组件:'import Pagination from '../packages/pagination/index.js"
includeComponentTemplate.push(render(IMPORT_TEMPLATE, {
name: componentName,
package: name
}));
if (['Loading', 'MessageBox', 'Notification', 'Message', 'InfiniteScroll'].indexOf(componentName) === -1) {
installTemplate.push(render(INSTALL_COMPONENT_TEMPLATE, {
name: componentName,
component: name
}));
}
if (componentName !== 'Loading') listTemplate.push(` ${componentName}`);
});
//通过render函数解析模板中的字符串
var template = render(MAIN_TEMPLATE, {
include: includeComponentTemplate.join(endOfLine),
install: installTemplate.join(',' + endOfLine),
version: process.env.VERSION || require('../../package.json').version,
list: listTemplate.join(',' + endOfLine)
});
fs.writeFileSync(OUTPUT_PATH, template);
console.log('[build entry] DONE:', OUTPUT_PATH);
Vue.use
和Vue.component
区别?
这篇文章讲的很好,可以进行参考,主要区别在于install
函数
[
{
"lang": "zh-CN",
"pages": {
"index": {}
}
} ,
{
"lang": "en-US",
"pages": {
"index": {}
}
}
]
Vue.use
注册插件,接收一个对象,参数必须具有install方法,
Vue.component
注册全局组件
build i8n
node build/bin/i18n.js
在examples\pages
目录生成不同的语言包,语言包类型在examples\i18n\page.json
中读取配置
page.json
'use strict';
var fs = require('fs');
var path = require('path');
var langConfig = require('../../examples/i18n/page.json');
langConfig.forEach(lang => {
try {
fs.statSync(path.resolve(__dirname, `../../examples/pages/${ lang.lang }`));
} catch (e) {
fs.mkdirSync(path.resolve(__dirname, `../../examples/pages/${ lang.lang }`));
}
//遍历配置项
Object.keys(lang.pages).forEach(page => {
var templatePath = path.resolve(__dirname, `../../examples/pages/template/${ page }.tpl`);
var outputPath = path.resolve(__dirname, `../../examples/pages/${ lang.lang }/${ page }.vue`);
var content = fs.readFileSync(templatePath, 'utf8');
var pairs = lang.pages[page];
Object.keys(pairs).forEach(key => {
content = content.replace(new RegExp(`<%=\\s*${ key }\\s*>`, 'g'), pairs[key]);
});
fs.writeFileSync(outputPath, content);
});
});
build version
node build/bin/version.js
为什么要把版本号列举出来?不能每次自动新增吗?
这个问题目前还没找到答案,有想法的小伙伴评论进行交流。
var fs = require('fs');
var path = require('path');
var version = process.env.VERSION || require('../../package.json').version;
var content = { '1.4.13': '1.4', '2.0.11': '2.0', '2.1.0': '2.1', '2.2.2': '2.2', '2.3.9': '2.3', '2.4.11': '2.4', '2.5.4': '2.5', '2.6.3': '2.6', '2.7.2': '2.7', '2.8.2': '2.8', '2.9.2': '2.9', '2.10.1': '2.10', '2.11.1': '2.11', '2.12.0': '2.12', '2.13.2': '2.13', '2.14.1': '2.14' };
if (!content[version]) content[version] = '2.15';
fs.writeFileSync(path.resolve(__dirname, '../../examples/versions.json'), JSON.stringify(content));
以上执行最终生成的内容有:
iconInit
对应examples\icon.json
build entry
对应src\index.js
i18n
对应examples\pages
version
对应examples\versions.json