Blame view

build/vite/plugin/transform/dynamic-import/index.ts 1.55 KB
1
2
// 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
3
// Special usage ,Only for this project
4
5
6
7
8
9
10
11
12
13
14
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', '');
}
vben authored
15
const dynamicImportTransform = function (enableDynamicImport: boolean): Transform {
16
17
18
  return {
    test({ path }) {
      // Only convert the file
19
      return (
vben authored
20
21
        path.includes('/src/router/helper/dynamicImport.ts') ||
        path.includes(`\\src\\router\\helper\\dynamicImport.ts`)
22
      );
23
24
    },
    transform({ code }) {
vben authored
25
      if (!enableDynamicImport) {
26
27
        return code;
      }
28
29
30
31
32
      // Only convert the dir
      try {
        const files = glob.sync('src/views/**/**.{vue,tsx}', { cwd: process.cwd() });
vben authored
33
        return `
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
        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
    `;
      } catch (error) {
        console.error(error);
        return code;
      }
    },
  };
};
export default dynamicImportTransform;