next.config.utils.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // workaround by https://github.com/martpie/next-transpile-modules/issues/143#issuecomment-817467144
  2. const fs = require('fs');
  3. const path = require('path');
  4. const nodeModulesPaths = [
  5. path.resolve(__dirname, '../../node_modules'),
  6. path.resolve(__dirname, '../../../../node_modules'),
  7. ];
  8. /**
  9. * @typedef { { ignorePackageNames: string[] } } Opts
  10. */
  11. /** @type {Opts} */
  12. const defaultOpts = { ignorePackageNames: [] };
  13. /**
  14. * @param scopes {string[]}
  15. */
  16. exports.listScopedPackages = (scopes, opts = defaultOpts) => {
  17. /** @type {string[]} */
  18. const scopedPackages = [];
  19. nodeModulesPaths.forEach((nodeModulesPath) => {
  20. fs.readdirSync(nodeModulesPath)
  21. .filter(name => scopes.includes(name))
  22. .forEach((scope) => {
  23. fs.readdirSync(path.resolve(nodeModulesPath, scope))
  24. .filter(name => !name.startsWith('.'))
  25. .forEach((folderName) => {
  26. const packageJsonPath = path.resolve(
  27. nodeModulesPath,
  28. scope,
  29. folderName,
  30. 'package.json',
  31. );
  32. if (fs.existsSync(packageJsonPath)) {
  33. const { name } = require(packageJsonPath);
  34. if (!opts.ignorePackageNames.includes(name)) {
  35. scopedPackages.push(name);
  36. }
  37. }
  38. });
  39. });
  40. });
  41. return scopedPackages;
  42. };
  43. /**
  44. * @param prefixes {string[]}
  45. */
  46. exports.listPrefixedPackages = (prefixes, opts = defaultOpts) => {
  47. /** @type {string[]} */
  48. const prefixedPackages = [];
  49. nodeModulesPaths.forEach((nodeModulesPath) => {
  50. fs.readdirSync(nodeModulesPath)
  51. .filter(name => prefixes.some(prefix => name.startsWith(prefix)))
  52. .filter(name => !name.startsWith('.'))
  53. .forEach((folderName) => {
  54. const packageJsonPath = path.resolve(
  55. nodeModulesPath,
  56. folderName,
  57. 'package.json',
  58. );
  59. if (fs.existsSync(packageJsonPath)) {
  60. const { name } = require(packageJsonPath);
  61. if (!opts.ignorePackageNames.includes(name)) {
  62. prefixedPackages.push(name);
  63. }
  64. }
  65. });
  66. });
  67. return prefixedPackages;
  68. };