index.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 (env: any = {}): Transform {
  14. return {
  15. test({ path }) {
  16. // Only convert the file
  17. return (
  18. path.includes('/src/utils/helper/dynamicImport.ts') ||
  19. path.includes(`\\src\\utils\\helper\\dynamicImport.ts`)
  20. );
  21. },
  22. transform({ code }) {
  23. const { VITE_DYNAMIC_IMPORT } = env;
  24. if (!VITE_DYNAMIC_IMPORT) {
  25. return code;
  26. }
  27. // Only convert the dir
  28. try {
  29. const files = glob.sync('src/views/**/**.{vue,tsx}', { cwd: process.cwd() });
  30. return `
  31. export default function (id) {
  32. switch (id) {
  33. ${files
  34. .map((p) =>
  35. ` case '${getPath(p)}': return () => import('${p
  36. .replace('src/views', '/@/views')
  37. .replace(/\/\//g, '/')}');`.replace('.tsx', '')
  38. )
  39. .join('\n ')}
  40. default: return Promise.reject(new Error("Unknown variable dynamic import: " + id));
  41. }
  42. }\n\n
  43. `;
  44. } catch (error) {
  45. console.error(error);
  46. return code;
  47. }
  48. },
  49. };
  50. };
  51. export default dynamicImportTransform;