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
|
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 {
|
vben
authored
|
16
17
18
|
return {
test({ path }) {
// Only convert the file
|
vben
authored
|
19
|
return (
|
vben
authored
|
20
21
|
path.includes('/src/router/helper/dynamicImport.ts') ||
path.includes(`\\src\\router\\helper\\dynamicImport.ts`)
|
vben
authored
|
22
|
);
|
vben
authored
|
23
24
|
},
transform({ code }) {
|
vben
authored
|
25
|
if (!enableDynamicImport) {
|
vben
authored
|
26
27
|
return code;
}
|
vben
authored
|
28
|
|
vben
authored
|
29
30
31
32
|
// Only convert the dir
try {
const files = glob.sync('src/views/**/**.{vue,tsx}', { cwd: process.cwd() });
|
vben
authored
|
33
|
return `
|
vben
authored
|
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;
|