You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.5 KiB

2 years ago
  1. 'use strict';
  2. const path = require('path');
  3. const basePath = require('./path');
  4. const fileHandle = require('./fileHepler');
  5. const fs = require("fs");
  6. const clog = require('./clog');
  7. /**
  8. * 递归创建目录
  9. * @param dirname
  10. * @returns {boolean}
  11. */
  12. const mkdirsSync = dirname => {
  13. if (fs.existsSync(dirname)) {
  14. return true;
  15. } else {
  16. if (mkdirsSync(path.dirname(dirname))) {
  17. fs.mkdirSync(dirname);
  18. return true;
  19. }
  20. }
  21. };
  22. let autoload = {
  23. /**
  24. * @description 自动加载模块
  25. * @param dir 加载路径
  26. * @param desc 描述
  27. * @param flieType 加载文件类型
  28. * @param type 加载返回数据类型Object|Array
  29. */
  30. createAutoload: function (dir, flieType=['js'], type = "object", desc='Utils',) {
  31. let autoladFile = fileHandle.getDirFiles(dir, flieType, ['.bak','autoload']),
  32. importStr = '',
  33. exportStr = '',
  34. count = 0;
  35. Object.keys(autoladFile).forEach((file) => {
  36. /**多层关系加载**/
  37. if (file.indexOf('bak') === -1) {
  38. let moduleName = this.handleFile(file);
  39. let modulePath = file;
  40. let str = '';
  41. if (count === 0) {
  42. str = `import ${moduleName} from './${modulePath}';`;
  43. exportStr += `${moduleName}`;
  44. } else {
  45. str = `
  46. import ${moduleName} from './${modulePath}';`;
  47. exportStr += `,
  48. ${moduleName}`;
  49. }
  50. importStr += str;
  51. count++;
  52. }
  53. });
  54. /**读取文件,并替换文件内容**/
  55. let buffer = fs.readFileSync(path.join(basePath.buildTemplateDirectory, 'autoload.txt'));
  56. let content = String(buffer);
  57. if(type === 'object') {
  58. exportStr = `{
  59. ${exportStr}
  60. }`;
  61. }
  62. if (type === 'array') {
  63. exportStr = `[
  64. ${exportStr}
  65. ]`;
  66. }
  67. content = content.replace(/@import_modules@/g, importStr);
  68. content = content.replace(/@modules_name@/g, exportStr);
  69. /**写文件**/
  70. let fd = fs.openSync(path.join(dir, 'autoload.js'), 'w');
  71. fs.writeFileSync(fd, content);
  72. fs.closeSync(fd);
  73. clog(`\n\n\n${desc} 加载完成,path:${path.join(dir, 'autoload.js')}`,'green');
  74. },
  75. handleFile(path) {
  76. if (path.indexOf('/') !== -1) {
  77. let temp = '';
  78. let arr = path.split('/');
  79. let len = arr.length;
  80. for (let i = 0; i < len; i++) {
  81. if (i === 0) temp = arr[i];
  82. else temp += arr[i].replace(arr[i][0], arr[i][0].toLocaleUpperCase());
  83. }
  84. return temp;
  85. } else {
  86. return path;
  87. }
  88. },
  89. };
  90. module.exports = autoload;