每次新增頁面復制粘貼?100多行源碼的 element-ui 的新增組件功能教你解愁

1. 前言

大家好,我是若川。最近組織了源碼共讀活動,感興趣的可以點此加我微信ruochuan12 參與,每周大家一起學習200行左右的源碼,共同進步。已進行三個月了,很多小伙伴表示收獲頗豐。

想學源碼,極力推薦之前我寫的《學習源碼整體架構系列》 包含20余篇源碼文章。

本文倉庫 element-analysis,求個star^_^[1]

最近組織了源碼共讀活動,大家一起學習源碼,每周學習200行左右的源碼,已進行到13期。于是搜尋各種值得我們學習,且代碼行數不多的源碼。

其中 element-ui[2]新建組件的源碼[3]100多行,非常值得我們學習。

可以通過 github1s.com 在線 VSCode 打開:https://github1s.com/ElemeFE/element/blob/dev/build/bin/new.js

閱讀本文,你將學到:

1.?學會調試學習源碼
2.?element-ui?如何初始化新的組件
3.?可以學以致用應用到自己開發的項目中,比如新增頁面等
4.?等等

2. 環境準備

2.1 克隆

#?推薦克隆我的項目,保證與文章同步
git?clone?https://github.com/lxchuan12/element-analysis.git
#?npm?i?-g?yarn
cd?element-analysis/element?&&?npm?run?dev#?或者克隆官方項目
git?clone?https://github.com/ElemeFE/element.git
#?npm?i?-g?yarn
cd?element?&&?npm?run?dev

2.2 看開源項目的 README 和貢獻文檔等

看開源項目,我們一般先看README,README.md[4] 中一般有貢獻指南[5]

開發環境搭建

首先你需要 Node.js 4+,yarn 和 npm 3+。注意:我們使用 yarn 進行依賴版本的鎖定,所以請不要使用 npm install 安裝依賴。

git?clone?git@github.com:ElemeFE/element.git
npm?run?dev#?open?http://localhost:8085

package.json

{"script":?{"bootstrap":?"yarn?||?npm?i","build:file":?"node?build/bin/iconInit.js?&?node?build/bin/build-entry.js?&?node?build/bin/i18n.js?&?node?build/bin/version.js","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 dev 時是先執行了 npm run bootstrap => yarn || npm i 命令,安裝好了依賴。

npm run build:file 應該留著下一篇文章講述。

組件開發規范

通過 make new 創建組件目錄結構,包含測試代碼、入口文件、文檔 如果包含父子組件,需要更改目錄結構,參考 Button組件內如果依賴了其他組件,需要在當前組件內引入,參考 Select

make 命令的配置對應根目錄 Makefile

#?element/Makefile
new:node?build/bin/new.js?$(filter-out?$@,$(MAKECMDGOALS))

通過查看 Makefile 文件我們知道了make new命令對應的是:node build/bin.new.js

接著我們來調試源碼。

2.3 調試源碼

在最新版的 VSCode 中,auto attach 功能,默認支持智能調試,如果發現不支持,可以通過快捷鍵 ctrl + shift + p 查看是否啟用。

ctrl + 快捷鍵打開終端。輸入如下命令,即可調試build/bin/new.js`。

make?new?ruochuan?若川組件
#?Ubuntu?和?Mac?支持?make?命令
#?不支持可以用?node
node?build/bin/new.js?ruochuan?若川組件
182ff47df6098be33322182e75cb50a2.png
調試截圖

更多調試細節可以看我的這篇文章:新手向:前端程序員必學基本技能——調試JS代碼

接著我們按調試來看主流程。

3. 主流程

我看完 build/bin/new.js 源碼畫了一張流程圖。畢竟俗話說得好,一圖勝千言。

fa7d6f2661d156eec653976e89f81b9a.png
流程圖

同時執行完命令后也新增和修改了若干文件,git diff 如下圖所示。

d2b36ec0b3556021967735b19eb1ef76.png
所有修改的文件

接著我們來看 build/bin/new.js 文件。

3.1 文件開頭判斷

'use?strict';console.log();
process.on('exit',?()?=>?{console.log();
});//?第一個參數沒傳遞報錯,退出進程
if?(!process.argv[2])?{console.error('[組件名]必填?-?Please?enter?new?component?name');process.exit(1);
}

關于 process 對象可以查看 阮一峰老師 process 對象[6]

process.argv 屬性返回一個數組,由命令行執行腳本時的各個參數組成。它的第一個成員總是 node,第二個成員是腳本文件名,其余成員是腳本文件的參數。

接著我們來看,引用的依賴等。

3.2 引用依賴等

//?路徑模塊
const?path?=?require('path');
//?文件模塊
const?fs?=?require('fs');
//?保存文件
const?fileSave?=?require('file-save');
//?轉駝峰
const?uppercamelcase?=?require('uppercamelcase');
//?第一個參數?組件名
const?componentname?=?process.argv[2];
//?第二個參數?組件中文名
const?chineseName?=?process.argv[3]?||?componentname;
//?轉駝峰
const?ComponentName?=?uppercamelcase(componentname);
//?package?路徑
const?PackagePath?=?path.resolve(__dirname,?'../../packages',?componentname);
//?const?Files?=?[];

其中 file-save[7] 依賴,顧名思義,且非常關鍵。我們可以在 node_module/file-save 查看一些信息。也可以在 https://npmjs.com 搜索其信息。

接著,我們來看文件模板。定義了若干文件模板,方便寫入到項目中。

3.3 文件模板 Files

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};`},{filename:?'src/main.vue',content:?`<template><div?class="el-${componentname}"></div>
</template><script>
export?default?{name:?'El${ComponentName}'
};
</script>`},
//???省略其他
];

接著我們繼續看添加對應的路徑到組件 json 配置中。

3.4 把 componentname 添加到 components.json

//?添加到?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');
81c02417893e5a4f6cb3bba3dbac9413.png
添加到 components.json

3.5 把 componentname.scss 添加到 index.scss

//?添加到?index.scss
const?sassPath?=?path.join(__dirname,?'../../packages/theme-chalk/src/index.scss');
const?sassImportText?=?`${fs.readFileSync(sassPath)}@import?"./${componentname}.scss";`;
fileSave(sassPath).write(sassImportText,?'utf8').end('\n');

3.6 把 componentname.d.ts 添加到 element-ui.d.ts

//?添加到?element-ui.d.ts
const?elementTsPath?=?path.join(__dirname,?'../../types/element-ui.d.ts');let?elementTsText?=?`${fs.readFileSync(elementTsPath)}
/**?${ComponentName}?Component?*/
export?class?${ComponentName}?extends?El${ComponentName}?{}`;const?index?=?elementTsText.indexOf('export')?-?1;
const?importString?=?`import?{?El${ComponentName}?}?from?'./${componentname}'`;elementTsText?=?elementTsText.slice(0,?index)?+?importString?+?'\n'?+?elementTsText.slice(index);fileSave(elementTsPath).write(elementTsText,?'utf8').end('\n');

3.7 創建 package

//?const?PackagePath?=?path.resolve(__dirname,?'../../packages',?componentname);
//?創建?package
Files.forEach(file?=>?{fileSave(path.join(PackagePath,?file.filename)).write(file.content,?'utf8').end('\n');
});
9be7d245356729c6f2206d2779e8fdbb.png
創建的文件

3.8 把新增的組件添加到 nav.config.json

const?navConfigFile?=?require('../../examples/nav.config.json');Object.keys(navConfigFile).forEach(lang?=>?{let?groups?=?navConfigFile[lang][4].groups;groups[groups.length?-?1].list.push({path:?`/${componentname}`,title:?lang?===?'zh-CN'?&&?componentname?!==?chineseName??`${ComponentName}?${chineseName}`:?ComponentName});
});fileSave(path.join(__dirname,?'../../examples/nav.config.json')).write(JSON.stringify(navConfigFile,?null,?'??'),?'utf8').end('\n');console.log('DONE!');
b0b4e462173ee1db711e41a67345ad49.png
nav

nav.config.json 的修改,新增的組件顯示在導航這里。其中有四次修改是對應四種語言。

6a3fe917bc73d60ce69903f033ce125c.png
nav 導航網站顯示

4. 總結

再次放出開頭的流程圖。

1fd9a3d99bba689bb8aa013b23e652f0.png
流程圖

通過看 element-ui[8]新建組件的源碼[9] 流程,我們學到了 file-save[10] 這么方便的寫入文件的庫等。

同時給我們啟發:公司項目新建頁面時,或者組件庫新增組件時,是不是可以類似做到的,一條命令省去一些繁雜重復的操作。

建議讀者克隆我的倉庫[11]動手實踐調試源碼學習。

后續也可以查看 file-save[12] 源碼實現等。

最后可以持續關注我@若川。歡迎加我微信 ruochuan12 交流,參與 源碼共讀 活動,大家一起學習源碼,共同進步。

參考資料

[1]

本文倉庫 element-analysis,求個star^_^: https://github.com/lxchuan12/element-analysis.git

[2]

更多點擊閱讀原文查看

最近組建了一個湖南人的前端交流群,如果你是湖南人可以加我微信?ruochuan12?私信 湖南 拉你進群。

推薦閱讀

1個月,200+人,一起讀了4周源碼
我歷時3年才寫了10余篇源碼文章,但收獲了100w+閱讀

老姚淺談:怎么學JavaScript?

我在阿里招前端,該怎么幫你(可進面試群)

c3b3a190da96ca55975077082af98300.gif

·················?若川簡介?·················

你好,我是若川,畢業于江西高校。現在是一名前端開發“工程師”。寫有《學習源碼整體架構系列》10余篇,在知乎、掘金收獲超百萬閱讀。
從2014年起,每年都會寫一篇年度總結,已經寫了7篇,點擊查看年度總結。
同時,最近組織了源碼共讀活動,幫助1000+前端人學會看源碼。公眾號愿景:幫助5年內前端人走向前列。

557207c4ef6271a66df203153cd191a4.png

識別方二維碼加我微信、拉你進源碼共讀

今日話題

略。分享、收藏、點贊、在看我的文章就是對我最大的支持~

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/275199.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/275199.shtml
英文地址,請注明出處:http://en.pswp.cn/news/275199.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

原子設計_您需要了解的有關原子設計的4件事

原子設計重點 (Top highlight)Industries such as Architecture or Industrial Design have developed smart modular systems for manufacturing extremely complex objects like airplanes, ships, and skyscrapers. Inspired by this, Atomic Design was proposed as a syst…

深度學習 Caffe 初始化流程理解(數據流建立)

之前在簡書的文章&#xff0c;搬遷過來 ^-^ 本文是作者原創&#xff0c;如有理解錯誤&#xff0c;懇請大家指出&#xff0c;如需引用&#xff0c;請注明出處。 #Caffe FeatureMap數據流的建立 ##用語解釋 FeatureMap: 輸入的圖片信息或者經過多層處理后的圖片信息。weights: 只…

C#中的Clipboard與ContextMenuStrip應用舉例

今天&#xff0c;突然想起了怎樣在一個文本中實現復制、剪切與粘貼的功能&#xff0c;并給這些功能添加右鍵的快捷方式。于是&#xff0c;就用自己的VS2008寫了一個簡單的小應用&#xff0c;以熟悉C#中剪貼板與快捷菜單的使用。 首先&#xff0c;我們不難發現&#xff0c;剪貼板…

控制臺ui_設計下一代控制臺UI

控制臺ui游戲UX (GAMES UX) Yesterday’s Sony presentation showed us the final look of the PlayStation 5, as well as an impressive of next-gen games that will be released with it. What we didn’t get to see, however, is the new operating system and it’s use…

寫給前端新手看的一些模塊化知識

大家好&#xff0c;我是若川。最近組織了源碼共讀活動&#xff0c;感興趣的可以點此加我微信ruochuan12 進群參與&#xff0c;每周大家一起學習200行左右的源碼&#xff0c;共同進步。已進行三個月了&#xff0c;很多小伙伴表示收獲頗豐。一、 為什么需要模塊化以前沒有模塊化時…

重學前端學習筆記(八)--JavaScript中的原型和類

筆記說明 重學前端是程劭非&#xff08;winter&#xff09;【前手機淘寶前端負責人】在極客時間開的一個專欄&#xff0c;每天10分鐘&#xff0c;重構你的前端知識體系&#xff0c;筆者主要整理學習過程的一些要點筆記以及感悟&#xff0c;完整的可以加入winter的專欄學習【原文…

代碼實現照片素描_我的代碼素描之旅

代碼實現照片素描In 2018 I started the process of consistently creating and posting my code sketches online. These are small animations I make with code and post on instagram. Through these sketches I tried to visually express my ideas using color, animatio…

GCC參數詳解

轉自&#xff1a;http://www.cnblogs.com/fence/archive/2009/12/18/1627138.html GCC參數詳解 gcc and g分別是gnu的c & c編譯器 gcc/g在執行編譯工作的時候&#xff0c;總共需要4步1.預處理,生成.i的文件[預處理器cpp]2.將預處理后的文件不轉換成匯編語言,生成文件.s[編…

真效率神器,UI稿智能轉換成前端代碼,準確率極高

大家好&#xff0c;我是若川。在這充滿網絡促銷活動的幾個月&#xff0c;倍感壓力的&#xff0c;除了你的口袋&#xff0c;是否還有程序員的發量呢&#xff1f;每年的雙十一、雙十二購物狂歡節&#xff0c;各大電商平臺都會上線讓消費者充滿購買欲望的活動頁面&#xff0c;而這…

PPT圖標的正確使用和插入與編輯形狀

PPT圖標的正確使用和插入與編輯形狀 通過圖標可以以符號的形式直觀地傳遞信息。 一&#xff0c;實戰&#xff1a;在銷售工作計劃中插入圖標 PowerPoint 2016中提供了多種類型的圖標&#xff0c;用戶可根據需要在幻燈片中插入所需的圖標。 二&#xff0c;實戰&#xff1a;更改銷…

幾個用于序列化的代碼片段

參考JavaScriptSerializer,一般用來做JSON格式化http://msdn.microsoft.com/zh-cn/library/system.web.script.serialization.javascriptserializer.aspx http://msdn.microsoft.com/zh-cn/library/system.web.script.serialization.javascriptconverter.aspxDataContractSeria…

桌面圖標擺放圖案_用圖標制作醒目的圖案

桌面圖標擺放圖案Level up your video calls with a custom backdrop created using Noun Project icons.使用使用Noun Project圖標創建的自定義背景來升級視頻通話。 The only thing more visually pleasing than a well-designed icon is a neat, eye-catching pattern made…

3個多月,近3000人參與的源碼共讀,誠邀加入~

大家好&#xff0c;我是若川。眾所周知&#xff0c;從8月份開始&#xff0c;我組織了源碼共讀活動&#xff0c;每周學習200行左右的源碼&#xff0c;到現在持續了3個多月&#xff0c;堅持答疑解惑。幫助了不少人&#xff0c;還是挺開心的。另外&#xff0c;涌現了很多優秀的讀者…

upc 組隊賽18 STRENGTH【貪心模擬】

STRENGTH 題目鏈接 題目描述 Strength gives you the confidence within yourself to overcome any fears, challenges or doubts. Feel the fear and do it anyway! If you have been going through a rough time and feel burnt out or stressed, the Strength card encourag…

JSONNull

最近用JSONObject&#xff0c;感覺比xml好用一些&#xff0c;json的打包和解包都比較清晰和容易&#xff0c;最近遇到一個問題&#xff0c;將一個JSON對象解析&#xff0c;存到hashmap中去&#xff0c;然后再從hashmap取出數據&#xff0c;遇到jsonnull的問題&#xff0c;本以為…

“這張圖告訴你什么?”

For data to be impactful, it must be understood.為了使數據具有影響力&#xff0c;必須理解它。 I’ve happily spent hundreds and hundreds of hours of my life watching users misunderstand data visualizations. I’m strangely hooked on it.我快樂地度過了數百個小…

我們從 UmiJS 遷移到了 Vite

大家好&#xff0c;我是若川。最近組織了源碼共讀活動&#xff0c;感興趣的可以點此加我微信ruochuan12 進群參與&#xff0c;每周大家一起學習200行左右的源碼&#xff0c;共同進步。已進行三個月了&#xff0c;很多小伙伴表示收獲頗豐。我們從 UmiJS遷移到 Vite 已經上線半年…

將DataTable的內容以EXCEl的形式導出到本地

1.在搞項目的時候一般會遇到&#xff0c;將GridView或者Repeater的內容以Excel的形式保存到本地&#xff0c;即導出功能。我總結了兩個方法。 方法一&#xff1a; 1 DataTable dt query.GetItems().GetDataTable();2 if (dt ! null)3 {4 …

智能家居數據庫設計_設計更智能的數據表

智能家居數據庫設計重點 (Top highlight)Data tables are hard. There are many different ways to think about them. So, naturally, the first step would be to figure out what your users need.數據表很難。 有許多不同的方式來考慮它們。 因此&#xff0c;自然地&#x…

可能是全網首個前端源碼共讀活動,誠邀你加入一起學習

大家好&#xff0c;我是若川。眾所周知&#xff0c;從8月份開始&#xff0c;我組織了源碼共讀活動&#xff0c;每周學習200行左右的源碼&#xff0c;到現在持續了3個多月&#xff0c;堅持答疑解惑。幫助了不少人&#xff0c;還是挺開心的。另外&#xff0c;涌現了很多優秀的讀者…