transform.ts 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Modified from
  2. // https://github.com/luxueyan/vite-transform-globby-import/blob/master/src/index.ts
  3. // TODO Currently, it is not possible to monitor file addition and deletion. The content has been changed, the cache problem?
  4. import { join } from 'path';
  5. import { lstatSync } from 'fs';
  6. import glob from 'glob';
  7. import { createResolver, Resolver } from 'vite/dist/node/resolver.js';
  8. import { Transform } from 'vite/dist/node/transform.js';
  9. const modulesDir: string = join(process.cwd(), '/node_modules/');
  10. interface SharedConfig {
  11. root?: string;
  12. alias?: Record<string, string>;
  13. resolvers?: Resolver[];
  14. }
  15. function template(template: string) {
  16. return (data: { [x: string]: any }) => {
  17. return template.replace(/#([^#]+)#/g, (_, g1) => data[g1] || g1);
  18. };
  19. }
  20. const globbyTransform = function (config: SharedConfig): Transform {
  21. const resolver = createResolver(
  22. config.root || process.cwd(),
  23. config.resolvers || [],
  24. config.alias || {}
  25. );
  26. const cache = new Map();
  27. const urlMap = new Map();
  28. return {
  29. test({ path }) {
  30. const filePath = path.replace('\u0000', ''); // why some path startsWith '\u0000'?
  31. try {
  32. return (
  33. !filePath.startsWith(modulesDir) &&
  34. /\.(vue|js|jsx|ts|tsx)$/.test(filePath) &&
  35. lstatSync(filePath).isFile()
  36. );
  37. } catch {
  38. return false;
  39. }
  40. },
  41. transform({ code, path, isBuild }) {
  42. let result = cache.get(path);
  43. if (!result) {
  44. const reg = /import\s+([\w\s{}*]+)\s+from\s+(['"])globby(\?path)?!([^'"]+)\2/g;
  45. const match = code.match(reg);
  46. if (!match) return code;
  47. const lastImport = urlMap.get(path);
  48. if (lastImport && match) {
  49. code = code.replace(lastImport, match[0]);
  50. }
  51. result = code.replace(reg, (_, g1, g2, g3, g4) => {
  52. const filePath = path.replace('\u0000', ''); // why some path startsWith '\u0000'?
  53. // resolve path
  54. const resolvedFilePath = g4.startsWith('.')
  55. ? resolver.resolveRelativeRequest(filePath, g4)
  56. : { pathname: resolver.requestToFile(g4) };
  57. const files = glob.sync(resolvedFilePath.pathname, { dot: true });
  58. let templateStr = 'import #name# from #file#'; // import default
  59. let name = g1;
  60. const m = g1.match(/\{\s*(\w+)(\s+as\s+(\w+))?\s*\}/); // import module
  61. const m2 = g1.match(/\*\s+as\s+(\w+)/); // import * as all module
  62. if (m) {
  63. templateStr = `import { ${m[1]} as #name# } from #file#`;
  64. name = m[3] || m[1];
  65. } else if (m2) {
  66. templateStr = 'import * as #name# from #file#';
  67. name = m2[1];
  68. }
  69. const temRender = template(templateStr);
  70. const groups: Array<string>[] = [];
  71. const replaceFiles = files.map((f, i) => {
  72. const file = g2 + resolver.fileToRequest(f) + g2;
  73. groups.push([name + i, file]);
  74. return temRender({ name: name + i, file });
  75. });
  76. urlMap.set(path, replaceFiles.join('\n'));
  77. return (
  78. replaceFiles.join('\n') +
  79. (g3 ? '\n' + groups.map((v) => `${v[0]}._path = ${v[1]}`).join('\n') : '') +
  80. `\nconst ${name} = { ${groups.map((v) => v[0]).join(',')} }\n`
  81. );
  82. });
  83. if (isBuild) cache.set(path, result);
  84. }
  85. return result;
  86. },
  87. };
  88. };
  89. export default globbyTransform;