index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * @desc: gen script command,make a new page generated by one click.
  3. * @author: nicejade
  4. */
  5. const fs = require('fs')
  6. const path = require('path')
  7. const colors = require('colors')
  8. const newFolderName = process.argv[2]
  9. String.prototype.firstUpperCase = function() {
  10. return this.replace(/\b(\w)/g, $1 => {
  11. return $1.toLowerCase()
  12. })
  13. }
  14. const resolve = dir => {
  15. return path.join(__dirname, '../..', dir)
  16. }
  17. const successExecPrint = msg => {
  18. console.log(
  19. colors.green(`✓ `) +
  20. colors.cyan(`${msg} `) +
  21. colors.green('task has been successfully executed.')
  22. )
  23. }
  24. function createNewPage(newFolderPath) {
  25. const mReg = new RegExp('@PAGE_CLASS_NAME', 'g')
  26. const pageContent = fs.readFileSync(`${__dirname}/template.ux`, 'UTF-8')
  27. const rootClassName = newFolderName
  28. .firstUpperCase()
  29. .replace(/([A-Z])/g, '-$1')
  30. .toLowerCase()
  31. const newContent = pageContent.replace(mReg, rootClassName)
  32. fs.mkdirSync(newFolderPath, 0777)
  33. fs.writeFile(`${newFolderPath}/index.ux`, newContent, error => {
  34. if (error) throw `Something went wrong: ${error}`
  35. })
  36. successExecPrint('Create New Page')
  37. }
  38. function saveRouter2Manifest() {
  39. const manifestPath = resolve('/src/manifest.json')
  40. let manifestConf = fs.readFileSync(manifestPath, 'UTF-8')
  41. manifestConf = JSON.parse(manifestConf)
  42. const routerPages = manifestConf.router.pages
  43. routerPages[`pages/${newFolderName}`] = {
  44. component: 'index'
  45. }
  46. manifestConf = JSON.stringify(manifestConf, null, 2)
  47. fs.writeFile(manifestPath, manifestConf, error => {
  48. if (error) throw `Something went wrong[@saveRouter2Manifest]: ${error}`
  49. })
  50. successExecPrint('Save Router Into Manifest')
  51. }
  52. function main() {
  53. if (!newFolderName) {
  54. return console.warn(
  55. `⚠️ Please enter the name of the page you want to create.`.underline.red
  56. )
  57. }
  58. const folderNameReg = /^[A-Z][[A-Za-z0-9]+$/
  59. if (!folderNameReg.test(newFolderName)) {
  60. return console.warn(
  61. `⚠️ Please enter the standard Folder name. Eg: XyzAbcde.`.underline.red
  62. )
  63. }
  64. const newFolderPath = path.join(__dirname, `../../src/pages/${newFolderName}`)
  65. const isExist = fs.existsSync(newFolderPath)
  66. if (isExist) {
  67. return console.warn(
  68. `⚠️ ${newFolderName} already exists in the /src/pages/ directory.`
  69. .underline.red
  70. )
  71. }
  72. createNewPage(newFolderPath)
  73. saveRouter2Manifest()
  74. }
  75. main()