generateView.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // generateView.js
  2. const chalk = require('chalk')
  3. const path = require('path')
  4. const fs = require('fs')
  5. const resolve = (...file) => path.resolve(__dirname, ...file)
  6. const log = message => console.log(chalk.green(`${message}`))
  7. const successLog = message => console.log(chalk.blue(`${message}`))
  8. const errorLog = error => console.log(chalk.red(`${error}`))
  9. const { vueTemplate } = require('./template')
  10. const generateFile = (path, data) => {
  11. if (fs.existsSync(path)) {
  12. errorLog(`${path}文件已存在`)
  13. return
  14. }
  15. return new Promise((resolve, reject) => {
  16. fs.writeFile(path, data, 'utf8', err => {
  17. if (err) {
  18. errorLog(err.message)
  19. reject(err)
  20. } else {
  21. resolve(true)
  22. }
  23. })
  24. })
  25. }
  26. log('请输入要生成的页面组件名称、会生成在 views/目录下')
  27. let componentName = ''
  28. process.stdin.on('data', async chunk => {
  29. const inputName = String(chunk).trim().toString()
  30. /**
  31. * Vue页面组件路径
  32. */
  33. let componentVueName = resolve('../src/views', inputName)
  34. // 如果不是以 .vue 结尾的话,自动加上
  35. if (!componentVueName.endsWith('.vue')) {
  36. componentVueName += '.vue'
  37. }
  38. /**
  39. * vue组件目录路径
  40. */
  41. const componentDirectory = path.dirname(componentVueName)
  42. const hasComponentExists = fs.existsSync(componentVueName)
  43. if (hasComponentExists) {
  44. errorLog(`${inputName}页面组件已存在,请重新输入`)
  45. return
  46. } else {
  47. log(`正在生成 component 目录 ${componentDirectory}`)
  48. await dotExistDirectoryCreate(componentDirectory)
  49. }
  50. try {
  51. if (inputName.includes('/')) {
  52. const inputArr = inputName.split('/')
  53. componentName = inputArr[inputArr.length - 1]
  54. } else {
  55. componentName = inputName
  56. }
  57. log(`正在生成 vue 文件 ${componentVueName}`)
  58. await generateFile(componentVueName, vueTemplate(componentName))
  59. successLog('生成成功')
  60. } catch (e) {
  61. errorLog(e.message)
  62. }
  63. process.stdin.emit('end')
  64. })
  65. process.stdin.on('end', () => {
  66. log('exit')
  67. process.exit()
  68. })
  69. function dotExistDirectoryCreate (directory) {
  70. return new Promise((resolve) => {
  71. mkdirs(directory, function () {
  72. resolve(true)
  73. })
  74. })
  75. }
  76. // 递归创建目录
  77. function mkdirs (directory, callback) {
  78. var exists = fs.existsSync(directory)
  79. if (exists) {
  80. callback()
  81. } else {
  82. mkdirs(path.dirname(directory), function () {
  83. fs.mkdirSync(directory)
  84. callback()
  85. })
  86. }
  87. }