通過(guò)npm或yarn自動(dòng)生成vue組件的方法示例
不知道大家每次新建組件的時(shí)候,是不是都要?jiǎng)?chuàng)建一個(gè)目錄,然后新增一個(gè).vue文件,然后寫(xiě)template、script、style這些東西,如果是公共組件,是不是還要新建一個(gè)index.js用來(lái)導(dǎo)出vue組件、雖然有vscode有代碼片段能實(shí)現(xiàn)自動(dòng)補(bǔ)全,但還是很麻煩,今天靈活運(yùn)用scripts工作流,自動(dòng)生成vue文件和目錄。
實(shí)踐步驟
安裝一下chalk,這個(gè)插件能讓我們的控制臺(tái)輸出語(yǔ)句有各種顏色區(qū)分
npm install chalk --save-dev yarn add chalk --save-dev
在根目錄中創(chuàng)建一個(gè) scripts 文件夾
新增一個(gè)generateComponent.js文件,放置生成組件的代碼
新增一個(gè)template.js文件,放置組件模板的代碼
template.js文件,里面的內(nèi)容可以自己自定義,符合當(dāng)前項(xiàng)目的模板即可
// template.js module.exports = { vueTemplate: compoenntName => { return `<template> <div class="${compoenntName}"> ${compoenntName}組件 </div> </template> <script> export default { name: '${compoenntName}' } </script> <style scoped lang="stylus" rel="stylesheet/stylus"> .${compoenntName} { } </style> ` }, entryTemplate: `import Main from './main.vue' export default Main` }
generateComponent.js生成vue目錄和文件的代碼
// generateComponent.js` const chalk = require('chalk') // 控制臺(tái)打印彩色 const path = require('path') const fs = require('fs') const resolve = (...file) => path.resolve(__dirname, ...file) const log = message => console.log(chalk.green(`${message}`)) const successLog = message => console.log(chalk.blue(`${message}`)) const errorLog = error => console.log(chalk.red(`${error}`)) const { vueTemplate, entryTemplate } = require('./template') const _ = process.argv.splice(2)[0] === '-com' const generateFile = (path, data) => { if (fs.existsSync(path)) { errorLog(`${path}文件已存在`) return } return new Promise((resolve, reject) => { fs.writeFile(path, data, 'utf8', err => { if (err) { errorLog(err.message) reject(err) } else { resolve(true) } }) }) } // 公共組件目錄src/base,全局注冊(cè)組件目錄src/base/global,頁(yè)面組件目錄src/components _ ? log('請(qǐng)輸入要生成的組件名稱(chēng)、如需生成全局組件,請(qǐng)加 global/ 前綴') : log('請(qǐng)輸入要生成的頁(yè)面組件名稱(chēng)、會(huì)生成在 components/目錄下') let componentName = '' process.stdin.on('data', async chunk => { const inputName = String(chunk).trim().toString() // 根據(jù)不同類(lèi)型組件分別處理 if (_) { // 組件目錄路徑 const componentDirectory = resolve('../src/base', inputName) // vue組件路徑 const componentVueName = resolve(componentDirectory, 'main.vue') // 入口文件路徑 const entryComponentName = resolve(componentDirectory, 'index.js') const hasComponentDirectory = fs.existsSync(componentDirectory) if (hasComponentDirectory) { errorLog(`${inputName}組件目錄已存在,請(qǐng)重新輸入`) return } else { log(`正在生成 component 目錄 ${componentDirectory}`) await dotExistDirectoryCreate(componentDirectory) } try { if (inputName.includes('/')) { const inputArr = inputName.split('/') componentName = inputArr[inputArr.length - 1] } else { componentName = inputName } log(`正在生成 vue 文件 ${componentVueName}`) await generateFile(componentVueName, vueTemplate(componentName)) log(`正在生成 entry 文件 ${entryComponentName}`) await generateFile(entryComponentName, entryTemplate) successLog('生成成功') } catch (e) { errorLog(e.message) } } else { const inputArr = inputName.split('/') const directory = inputArr[0] let componentName = inputArr[inputArr.length - 1] // 頁(yè)面組件目錄 const componentDirectory = resolve('../src/components', directory) // vue組件 const componentVueName = resolve(componentDirectory, `${componentName}.vue`) const hasComponentDirectory = fs.existsSync(componentDirectory) if (hasComponentDirectory) { log(`${componentDirectory}組件目錄已存在,直接生成vue文件`) } else { log(`正在生成 component 目錄 ${componentDirectory}`) await dotExistDirectoryCreate(componentDirectory) } try { log(`正在生成 vue 文件 ${componentName}`) await generateFile(componentVueName, vueTemplate(componentName)) successLog('生成成功') } catch (e) { errorLog(e.message) } } process.stdin.emit('end') }) process.stdin.on('end', () => { log('exit') process.exit() }) function dotExistDirectoryCreate (directory) { return new Promise((resolve) => { mkdirs(directory, function () { resolve(true) }) }) } // 遞歸創(chuàng)建目錄 function mkdirs (directory, callback) { var exists = fs.existsSync(directory) if (exists) { callback() } else { mkdirs(path.dirname(directory), function () { fs.mkdirSync(directory) callback() }) } }
配置package.json,scripts新增兩行命令,其中-com是為了區(qū)別是創(chuàng)建頁(yè)面組件還是公共組件
"scripts": { "new:view":"node scripts/generateComponent", "new:com": "node scripts/generateComponent -com" },
執(zhí)行
npm run new:view // 生成頁(yè)組件 npm run new:com // 生成基礎(chǔ)組件 或者 yarn run new:view // 生成頁(yè)組件 yarn run new:com // 生成基礎(chǔ)組件
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Vue自定義v-has指令,做按鈕權(quán)限判斷的步驟
這篇文章主要介紹了Vue自定義v-has指令,做按鈕權(quán)限判斷的步驟,幫助大家更好的理解和學(xué)習(xí)使用vue框架,感興趣的朋友可以了解下2021-04-04vue項(xiàng)目中Toast字體過(guò)小,沒(méi)有邊距的解決方案
這篇文章主要介紹了vue項(xiàng)目中Toast字體過(guò)小,沒(méi)有邊距的解決方案。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04解決VUE 在IE下出現(xiàn)ReferenceError: Promise未定義的問(wèn)題
這篇文章主要介紹了解決VUE 在IE下出現(xiàn)ReferenceError: Promise未定義的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-11-11利用vue實(shí)現(xiàn)密碼輸入框/驗(yàn)證碼輸入框
這篇文章主要為大家詳細(xì)介紹了如何利用vue實(shí)現(xiàn)密碼輸入框或驗(yàn)證碼輸入框的效果,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以參考一下2023-08-08