携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第2天,点击查看活动详情
- 本文参加了由公众号@若川视野 发起的每周源码共读活动, 点击了解详情一起参与。
- 这是源码共读的第15期,链接:www.yuque.com/ruochuan12/…。
摘要
本次学习的是 elementui 创建新组件时用到的工具代码,通过一行命令 make new new-component
可以非常方便快捷地生成新组件的相关文件。
这里使用了 make 命令,而 windows 系统需要额外安装,安装 make 可以参考此文 ,如果在线下载失败可以根据文章中第二步安装信息说明下载对应的文件。
源码分析
首先查看下根目录下的 Makefile
文件,可以看到 make new
命令实际上是执行的是 node build/bin/new.js $(filter-out $@,$(MAKECMDGOALS))
,因此我们需要查看的源码位置位于 build\bin\new.js
下面针对源码中的各个片段进行分析
-
组件名称必填判断,如果执行
make new
命令后并未携带组件名参数,则要退出命令的执行。关于process
对象可以查看 阮一峰老师 process 对象if (!process.argv[2]) { console.error("[组件名]必填 - Please enter new component name"); process.exit(1); }
-
引入需要用到的包,path —— 获取路径, fs —— 读取文件, file-save —— 保存文件,uppercamelcase —— 名字转大驼峰(帕斯卡命名法)。js 中常见命名方式
const path = require("path"); const fs = require("fs"); const fileSave = require("file-save"); const uppercamelcase = require("uppercamelcase");
-
获取了组件名称,以及
packages
的路径,并定义了需要在packages
/examples
/test
文件路径下生成和新创建组件相关的代码文件模板const componentname = process.argv[2]; const chineseName = process.argv[3] || componentname; const ComponentName = uppercamelcase(componentname); const PackagePath = path.resolve(__dirname, "../../packages", componentname); const Files = [ { filename: "index.js", content: `import ${ComponentName} from './src/main'; /* istanbul ignore next */ ${ComponentName}.install = function(Vue) { Vue.component(${ComponentName}.name, ${ComponentName}); }; export default ${ComponentName};`, } ... ];
-
将新组件信息添加到 components.json
const componentsFile = require("../../components.json"); if (componentsFile[componentname]) { console.error(`${componentname} 已存在.`); process.exit(1); } componentsFile[componentname] = `./packages/${componentname}/index.js`; fileSave(path.join(__dirname, "../../components.json")) .write(JSON.stringify(componentsFile, null, " "), "utf8") .end("\n");
-
后面的代码内容大同小异,都是写入文件工作。 还需要操作的文件有:
index.scss
,element-ui.d.ts
,nav.config.json
,
总结
总的来说本次的源码也是比较简单的,不过实现的功能确让人眼前一亮,通过编写代码的方式来简化不少需要耗时耗力的初始化、配置性质的工作。 在阅读的过程中,我突然有个灵感,目前的项目需要一个新页面时,需要如下两个步骤:
- 创建页面文件
- 配置 router
- ···(目前项目没有其它需要做的了,但是别的项目不一定呀)
这样的工作是不是就可以写这样一个脚本来替代呢~~
说干就干,花了一个下午的时间编写了一个创建需要配置路由的组件文件页面创建脚本,主要就包括创建页面和配置路由两个步骤。
这里简单先贴一下创建页面组件文件的相关代码,路由页面的相对复杂一丢丢,有兴趣的小伙伴可以交流一下呀~
const componentsPath = process.argv.slice(2);
const fileName = componentsPath[componentsPath.length - 1];
if (!fileName.endsWith(".vue")) {
componentsPath.push(INDEX_VUE);
}
const componentFile = path.resolve(
__dirname,
"../src/views",
componentsPath.join("/")
);
if (fs.existsSync(componentFile)) {
console.log(`${componentFile} 已存在`);
process.exit(1);
}
收获
本次源码阅读的收获颇丰,简单总结如下:
- 了解了 makefile 和如何在 windows 系统下安装 make 命令
- 了解了 node 中的
process
对象 - 复习了命名方式
- 学到了 node 中的
fs
,file-save
的使用 - 编写了创建页面组件文件的小脚本,能够提高项目的开发效率