vue-vben-admin/build/vite/plugin/transform/dynamic-import/index.ts

55 lines
1.6 KiB
TypeScript
Raw Normal View History

2020-11-08 23:13:47 +08:00
// 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
// Special usage Only for this project
2020-11-08 23:13:47 +08:00
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', '');
}
2020-12-01 21:02:37 +08:00
const dynamicImportTransform = function (enableDynamicImport: boolean): Transform {
2020-11-08 23:13:47 +08:00
return {
test({ path }) {
// Only convert the file
return (
2020-12-03 21:49:32 +08:00
path.includes('/src/router/helper/dynamicImport.ts') ||
path.includes(`\\src\\router\\helper\\dynamicImport.ts`)
);
2020-11-08 23:13:47 +08:00
},
transform({ code }) {
2020-12-01 21:02:37 +08:00
if (!enableDynamicImport) {
2020-11-08 23:13:47 +08:00
return code;
}
2020-11-08 23:13:47 +08:00
// Only convert the dir
try {
const files = glob.sync('src/views/**/**.{vue,tsx}', { cwd: process.cwd() });
2020-11-12 22:20:15 +08:00
return `
2020-11-08 23:13:47 +08:00
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;