index.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import path from 'node:path';
  2. import fs from 'node:fs/promises';
  3. import type {Plugin} from '@docusaurus/types';
  4. type Options = {
  5. sourceDir: string;
  6. routeBasePath: string;
  7. };
  8. export default function copyMdPlugin(
  9. _context: unknown,
  10. options: Options,
  11. ): Plugin<void> {
  12. return {
  13. name: 'copy-md',
  14. async postBuild({siteDir, outDir}) {
  15. const src = path.join(siteDir, options.sourceDir);
  16. const dest = path.join(outDir, options.routeBasePath);
  17. await fs.mkdir(dest, {recursive: true});
  18. await copyMarkdownFiles(src, dest);
  19. },
  20. };
  21. }
  22. async function copyMarkdownFiles(src: string, dest: string): Promise<void> {
  23. const entries = await fs.readdir(src, {withFileTypes: true});
  24. for (const entry of entries) {
  25. const srcPath = path.join(src, entry.name);
  26. const destPath = path.join(dest, entry.name);
  27. if (entry.isDirectory()) {
  28. await fs.mkdir(destPath, {recursive: true});
  29. await copyMarkdownFiles(srcPath, destPath);
  30. continue;
  31. }
  32. if (entry.isFile() && /\.(md|mdx)$/i.test(entry.name)) {
  33. await fs.copyFile(srcPath, destPath);
  34. }
  35. }
  36. }