index.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. import glob from 'glob';
  4. import { Transform } from 'vite/dist/node/transform.js';
  5. function getPath(path: string) {
  6. const lastIndex = path.lastIndexOf('.');
  7. if (lastIndex !== -1) {
  8. path = path.substring(0, lastIndex);
  9. }
  10. return path.replace('src/views', '');
  11. }
  12. const dynamicImportTransform = function (env: any = {}): Transform {
  13. return {
  14. test({ path }) {
  15. // Only convert the file
  16. return (
  17. path.includes('/src/utils/helper/dynamicImport.ts') ||
  18. path.includes(`\\src\\utils\\helper\\dynamicImport.ts`)
  19. );
  20. },
  21. transform({ code }) {
  22. const { VITE_DYNAMIC_IMPORT } = env;
  23. if (!VITE_DYNAMIC_IMPORT) {
  24. return code;
  25. }
  26. // if (!isBuild) return code;
  27. // Only convert the dir
  28. try {
  29. const files = glob.sync('src/views/**/**.{vue,tsx}', { cwd: process.cwd() });
  30. const _code = `
  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. return _code;
  45. } catch (error) {
  46. console.error(error);
  47. return code;
  48. }
  49. },
  50. };
  51. };
  52. export default dynamicImportTransform;