首先咱們安裝一些命令行的插件, 開發依賴就能夠git
yarn add fs-extra chalk log-symbols -D
複製代碼
// 拿到命令行的參數去生成對應的文件 // 拿到命令行輸入的模塊名 const moduleName = process.argv[2]; // 默認模版目錄 const componentModulePath = path.resolve( "./template" ); // 生成pages裏的component const assetsModulePath = path.resolve("./assets"); const localeModulePath = path.resolve("./locales"); // 輸出的目標目錄 const componentTargetPath = path.resolve("src/views"); // 對應輸出的目標文件 const assetsTargetPath = path.resolve("src/assets"); const localeTargetPath = path.resolve("src/locales"); 複製代碼
@param componentModulePath(要拷貝的模版路徑) @param componentTargetPath(輸出的目標路徑) @param moduleNme(命令行拿到的 模塊名) createComponent(componentModulePath, componentTargetPath, moduleName); createComponent(assetsModulePath, assetsTargetPath, moduleName); createComponent(localeModulePath, localeTargetPath, moduleName); const createComponent = (demoPath, targetpath, name) => { console.log(symbols.success, chalk.green("開始建立..........,請稍候")); fs.copy(demoPath, `${targetpath}/${name}`) // 拷貝模板文件到目標目錄 .then(() => { reWrite(`${targetpath}/${name}`, name); // 生成文件 console.log(symbols.success, chalk.green("建立成功")); }) .catch(err => { console.log(symbols.error, chalk.red("建立失敗", err)); }); const reWrite = (path, name) => { const files = fs.readdirSync(path); files.forEach(file => { const fileName = `${path}/${file}`; if (fs.statSync(fileName).isFile()) { const content = fs.readFileSync(fileName).toString(); // 建立子級組件XXX/yy,截取yy const demoName = name.split("/").reverse()[0]; // 截取組件名-, 則寫入的組件名採用大駝峯 const result = content.replace(/template/g, stringToCamel(demoName)); fs.writeFileSync(fileName, result); } else { reWrite(fileName, name); } }); }; // 將字符串轉化成大駝峯 const stringToCamel = str => { let temp = str.split("-"); for (let i = 0; i < temp.length; i++) { temp[i] = temp[i][0].toUpperCase() + temp[i].slice(1); } return temp.join(""); }; }; 複製代碼
github傳送門 github.com/promotion-x…github