next.config.utils.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // workaround by https://github.com/martpie/next-transpile-modules/issues/143#issuecomment-817467144
  2. import fs from 'node:fs';
  3. import path from 'node:path';
  4. const nodeModulesPaths = [
  5. path.resolve(__dirname, '../../node_modules'),
  6. path.resolve(__dirname, '../../../../node_modules'),
  7. ];
  8. interface Opts {
  9. ignorePackageNames: string[];
  10. }
  11. const defaultOpts: Opts = { ignorePackageNames: [] };
  12. export const listPrefixedPackages = (
  13. prefixes: string[],
  14. opts: Opts = defaultOpts,
  15. ): string[] => {
  16. const prefixedPackages: string[] = [];
  17. nodeModulesPaths.forEach((nodeModulesPath) => {
  18. fs.readdirSync(nodeModulesPath)
  19. .filter((name) => prefixes.some((prefix) => name.startsWith(prefix)))
  20. .filter((name) => !name.startsWith('.'))
  21. .forEach((folderName) => {
  22. const packageJsonPath = path.resolve(
  23. nodeModulesPath,
  24. folderName,
  25. 'package.json',
  26. );
  27. if (fs.existsSync(packageJsonPath)) {
  28. const { name } = JSON.parse(
  29. fs.readFileSync(packageJsonPath, 'utf-8'),
  30. ) as { name: string };
  31. if (!opts.ignorePackageNames.includes(name)) {
  32. prefixedPackages.push(name);
  33. }
  34. }
  35. });
  36. });
  37. return prefixedPackages;
  38. };