generateComponent.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // generateComponent.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, entryTemplate } = 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('请输入要生成的组件名称、如需生成全局组件,请加 global/ 前缀')
  27. let componentName = ''
  28. process.stdin.on('data', async chunk => {
  29. const inputName = String(chunk).trim().toString()
  30. /**
  31. * 组件目录路径
  32. */
  33. const componentDirectory = resolve('../src/components', inputName)
  34. /**
  35. * vue组件路径
  36. */
  37. const componentVueName = resolve(componentDirectory, 'main.vue')
  38. /**
  39. * 入口文件路径
  40. */
  41. const entryComponentName = resolve(componentDirectory, 'index.js')
  42. const hasComponentDirectory = fs.existsSync(componentDirectory)
  43. if (hasComponentDirectory) {
  44. errorLog(`${inputName}组件目录已存在,请重新输入`)
  45. return
  46. } else {
  47. log(`正在生成 component 目录 ${componentDirectory}`)
  48. await dotExistDirectoryCreate(componentDirectory)
  49. // fs.mkdirSync(componentDirectory);
  50. }
  51. try {
  52. if (inputName.includes('/')) {
  53. const inputArr = inputName.split('/')
  54. componentName = inputArr[inputArr.length - 1]
  55. } else {
  56. componentName = inputName
  57. }
  58. log(`正在生成 vue 文件 ${componentVueName}`)
  59. await generateFile(componentVueName, vueTemplate(componentName))
  60. log(`正在生成 entry 文件 ${entryComponentName}`)
  61. await generateFile(entryComponentName, entryTemplate)
  62. successLog('生成成功')
  63. } catch (e) {
  64. errorLog(e.message)
  65. }
  66. process.stdin.emit('end')
  67. })
  68. process.stdin.on('end', () => {
  69. log('exit')
  70. process.exit()
  71. })
  72. function dotExistDirectoryCreate (directory) {
  73. return new Promise((resolve) => {
  74. mkdirs(directory, function () {
  75. resolve(true)
  76. })
  77. })
  78. }
  79. // 递归创建目录
  80. function mkdirs (directory, callback) {
  81. var exists = fs.existsSync(directory)
  82. if (exists) {
  83. callback()
  84. } else {
  85. mkdirs(path.dirname(directory), function () {
  86. fs.mkdirSync(directory)
  87. callback()
  88. })
  89. }
  90. }