index.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. const path = require('path')
  2. const CONFIG = {
  3. includes: ['path', 'aliasPath', 'name']
  4. }
  5. const rootPath = path.resolve(process.cwd(), 'node_modules');
  6. /** 解析绝对路径
  7. * @param {Object} dir
  8. */
  9. function resolvePath(dir) {
  10. return path.resolve(rootPath, dir);
  11. }
  12. class TransformPages {
  13. constructor(config) {
  14. config = {
  15. ...CONFIG,
  16. ...config
  17. };
  18. this.CONFIG = config;
  19. this.webpack = require(resolvePath('webpack'));
  20. this.uniPagesJSON = require(resolvePath('@dcloudio/uni-cli-shared/lib/pages.js'));
  21. this.routes = this.getPagesRoutes().concat(this.getNotMpRoutes());
  22. }
  23. /**
  24. * 获取所有pages.json下的内容 返回json
  25. */
  26. get pagesJson() {
  27. return this.uniPagesJSON.getPagesJson();
  28. }
  29. /**
  30. * 通过读取pages.json文件 生成直接可用的routes
  31. */
  32. getPagesRoutes(pages = this.pagesJson.pages, rootPath = null) {
  33. const routes = [];
  34. for (let i = 0; i < pages.length; i++) {
  35. const item = pages[i];
  36. const route = {};
  37. for (let j = 0; j < this.CONFIG.includes.length; j++) {
  38. const key = this.CONFIG.includes[j];
  39. let value = item[key];
  40. if (key === 'path') {
  41. value = rootPath ? `/${rootPath}/${value}` : `/${value}`
  42. }
  43. if (key === 'aliasPath' && i == 0 && rootPath == null) {
  44. route[key] = route[key] || '/'
  45. } else if (value !== undefined) {
  46. route[key] = value;
  47. }
  48. }
  49. routes.push(route);
  50. }
  51. return routes;
  52. }
  53. /**
  54. * 解析小程序分包路径
  55. */
  56. getNotMpRoutes() {
  57. const {
  58. subPackages
  59. } = this.pagesJson;
  60. let routes = [];
  61. if (subPackages == null || subPackages.length == 0) {
  62. return [];
  63. }
  64. for (let i = 0; i < subPackages.length; i++) {
  65. const subPages = subPackages[i].pages;
  66. const root = subPackages[i].root;
  67. const subRoutes = this.getPagesRoutes(subPages, root);
  68. routes = routes.concat(subRoutes)
  69. }
  70. return routes
  71. }
  72. /**
  73. * 单条page对象解析
  74. * @param {Object} pageCallback
  75. * @param {Object} subPageCallback
  76. */
  77. parsePages(pageCallback, subPageCallback) {
  78. this.uniPagesJSON.parsePages(this.pagesJson, pageCallback, subPageCallback)
  79. }
  80. }
  81. module.exports = TransformPages