generateView.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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)
  30. .trim()
  31. .toString();
  32. /**
  33. * Vue页面组件路径
  34. */
  35. let componentVueName = resolve("../src/views", inputName);
  36. // 如果不是以 .vue 结尾的话,自动加上
  37. if (!componentVueName.endsWith(".vue")) {
  38. componentVueName += ".vue";
  39. }
  40. /**
  41. * vue组件目录路径
  42. */
  43. const componentDirectory = path.dirname(componentVueName);
  44. const hasComponentExists = fs.existsSync(componentVueName);
  45. if (hasComponentExists) {
  46. errorLog(`${inputName}页面组件已存在,请重新输入`);
  47. return;
  48. } else {
  49. log(`正在生成 component 目录 ${componentDirectory}`);
  50. await dotExistDirectoryCreate(componentDirectory);
  51. }
  52. try {
  53. if (inputName.includes("/")) {
  54. const inputArr = inputName.split("/");
  55. componentName = inputArr[inputArr.length - 1];
  56. } else {
  57. componentName = inputName;
  58. }
  59. log(`正在生成 vue 文件 ${componentVueName}`);
  60. await generateFile(componentVueName, vueTemplate(componentName));
  61. successLog("生成成功");
  62. } catch (e) {
  63. errorLog(e.message);
  64. }
  65. process.stdin.emit("end");
  66. });
  67. process.stdin.on("end", () => {
  68. log("exit");
  69. process.exit();
  70. });
  71. function dotExistDirectoryCreate(directory) {
  72. return new Promise(resolve => {
  73. mkdirs(directory, function() {
  74. resolve(true);
  75. });
  76. });
  77. }
  78. // 递归创建目录
  79. function mkdirs(directory, callback) {
  80. var exists = fs.existsSync(directory);
  81. if (exists) {
  82. callback();
  83. } else {
  84. mkdirs(path.dirname(directory), function() {
  85. fs.mkdirSync(directory);
  86. callback();
  87. });
  88. }
  89. }