123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- // generateView.js
- const chalk = require('chalk')
- 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 {jsFileTemplate,vueFileTemplate } = require('./templateForFiles')
- 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)
- }
- })
- })
- }
- log('请输入要生成的页面组件名称、会生成在 views/目录下')
- let componentName = ''
- process.stdin.on('data', async chunk => {
- const inputName = String(chunk).trim().toString()
- /**
- * Vue页面组件路径
- */
- let componentVueName = resolve('../src/views', inputName)
- let componentJsName = componentVueName+'.js'
- let componentLessName = componentVueName+'.less'
- let componentHtmlName = componentVueName+'.html'
- // 如果不是以 .vue 结尾的话,自动加上
- if (!componentVueName.endsWith('.vue')) {
- componentVueName += '.vue'
- }
- /**
- * vue组件目录路径
- */
- const componentDirectory = path.dirname(componentVueName)
- const hasComponentExists = fs.existsSync(componentVueName)
- if (hasComponentExists) {
- errorLog(`${inputName}页面组件已存在,请重新输入`)
- 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, vueFileTemplate(componentName))
- log(`正在生成 js 文件 ${componentJsName}`)
- await generateFile(componentJsName, jsFileTemplate(componentName))
- log(`正在生成 html 文件 ${componentHtmlName}`)
- await generateFile(componentHtmlName, '')
- log(`正在生成 less 文件 ${componentLessName}`)
- await generateFile(componentLessName, '')
- 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)
- })
- })
- }
- // 递归创建目录
- function mkdirs (directory, callback) {
- var exists = fs.existsSync(directory)
- if (exists) {
- callback()
- } else {
- mkdirs(path.dirname(directory), function () {
- fs.mkdirSync(directory)
- callback()
- })
- }
- }
|