背景
我們知道許多框架會提供一個腳手架工具,我們先下載安裝腳手架工具,然後再通過腳手架命令行來創建項目。在[email protected]
中引入了npm init <initializer>
的語法。簡單來說就是你執行npm init cabloy
的話,npm會補全模塊名爲create-cabloy
,並執行npx create-cabloy
CabloyJS提供的命令
我們知道,在CabloyJS中創建一個項目,使用如下命令:
npm init cabloy cabloy-demo --type=cabloy
在項目中創建一個業務模塊,使用如下命令:
npm init cabloy src/module/test-todo --type=module-business
npm init cabloy具體流程
下面我們具體說一下這一行npm init cabloy
具體做了哪些事情:
-
關於
npm init cabloy
:npm會自動下載模塊create-cabloy
,然後執行create-cabloy
,順便把後面的參數傳入 -
模塊
create-cabloy
會自動執行模塊egg-born
,順便把後面的參數傳入。(爲什麼這樣跳轉一次?是因爲egg-born
命令行工具早就實現了,而npm init cabloy
的機制是npm後期引入的)egg-born
就是我們在上面提到的腳手架工具 -
模塊
egg-born
會下載模塊egg-born-init-config
-
模塊
egg-born-init-config
的package.json
文件中定義了三個模版:每個模版對應一個npm模塊。比如模版module-business
對應模塊egg-born-template-module-business
-
如果用戶通過
--type
指定了module-business
,那麼就會自動下載模塊egg-born-template-module-business
-
模塊
egg-born-template-module-business
包含兩部分:index.js
文件:定義了一些變量,egg-born
會使用這些變量收集當前模版的參數,如name/description等等boilerplate
目錄:包含一套文件模版,egg-born
會自動替換文件模版裏面的參數,然後輸出到預定的目錄,在這個例子中就是src/module/test-todo