vben
authored
|
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
|
vben
authored
|
3
|
// Special usage ,Only for this project
|
vben
authored
|
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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
|
vben
authored
|
19
20
21
22
|
return (
path.includes('/src/utils/helper/dynamicImport.ts') ||
path.includes(`\\src\\utils\\helper\\dynamicImport.ts`)
);
|
vben
authored
|
23
24
|
},
transform({ code }) {
|
vben
authored
|
25
26
|
const { VITE_DYNAMIC_IMPORT } = env;
if (!VITE_DYNAMIC_IMPORT) {
|
vben
authored
|
27
28
|
return code;
}
|
vben
authored
|
29
|
|
vben
authored
|
30
31
32
33
|
// Only convert the dir
try {
const files = glob.sync('src/views/**/**.{vue,tsx}', { cwd: process.cwd() });
|
vben
authored
|
34
|
return `
|
vben
authored
|
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
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;
|