index.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Used to import all files under `src/views`
  2. // The built-in dynamic import of vite cannot meet the needs of importing all files under views
  3. // Special usage ,Only for this project
  4. import glob from 'glob';
  5. import { Transform } from 'vite/dist/node/transform.js';
  6. function getPath(path: string) {
  7. const lastIndex = path.lastIndexOf('.');
  8. if (lastIndex !== -1) {
  9. path = path.substring(0, lastIndex);
  10. }
  11. return path.replace('src/views', '');
  12. }
  13. const dynamicImportTransform = function (enableDynamicImport: boolean): Transform {
  14. return {
  15. test({ path }) {
  16. // Only convert the file
  17. return (
  18. path.includes('/src/router/helper/dynamicImport.ts') ||
  19. path.includes(`\\src\\router\\helper\\dynamicImport.ts`)
  20. );
  21. },
  22. transform({ code }) {
  23. if (!enableDynamicImport) {
  24. return code;
  25. }
  26. // Only convert the dir
  27. try {
  28. const files = glob.sync('src/views/**/**.{vue,tsx}', { cwd: process.cwd() });
  29. return `
  30. export default function (id) {
  31. switch (id) {
  32. ${files
  33. .map((p) =>
  34. ` case '${getPath(p)}': return () => import('${p
  35. .replace('src/views', '/@/views')
  36. .replace(/\/\//g, '/')}');`.replace('.tsx', '')
  37. )
  38. .join('\n ')}
  39. default: return Promise.reject(new Error("Unknown variable dynamic import: " + id));
  40. }
  41. }\n\n
  42. `;
  43. } catch (error) {
  44. console.error(error);
  45. return code;
  46. }
  47. },
  48. };
  49. };
  50. export default dynamicImportTransform;