index.ts 1.5 KB
Newer Older
V
vben 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
// Used to import all files under `src/views`

// The built-in dynamic import of vite cannot meet the needs of importing all files under views

import glob from 'glob';
import { Transform } from 'vite/dist/node/transform.js';

function getPath(path: string) {
  const lastIndex = path.lastIndexOf('.');
  if (lastIndex !== -1) {
    path = path.substring(0, lastIndex);
  }
  return path.replace('src/views', '');
}

const dynamicImportTransform = function (env: any = {}): Transform {
  return {
    test({ path }) {
      // Only convert the file
      return path.includes('/src/utils/helper/dynamicImport.ts');
    },
    transform({ code }) {
      const { VITE_GEN_MENU_MODE = '' } = env;
      if (VITE_GEN_MENU_MODE !== 'BACK') {
        return code;
      }
      // if (!isBuild) return code;
      // Only convert the dir
      try {
        const files = glob.sync('src/views/**/**.{vue,tsx}', { cwd: process.cwd() });

        const _code = `
        export default function (id) {
           switch (id) {
          ${files

            .map((p) =>
              `   case '${getPath(p)}': return  () => import('${p
                .replace('src/views', '/@/views')
                .replace(/\/\//g, '/')}');`.replace('.tsx', '')
            )
            .join('\n  ')}
          default: return Promise.reject(new Error("Unknown variable dynamic import: " + id));
           }
    }\n\n
    `;
        return _code;
      } catch (error) {
        console.error(error);
        return code;
      }
    },
  };
};
export default dynamicImportTransform;