next.config.utils.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 nodeModulesPath = path.resolve(__dirname, '../../../../node_modules');
  5. /**
  6. * @typedef { { ignorePackageNames: string[] } } Opts
  7. */
  8. /** @type {Opts} */
  9. const defaultOpts = { ignorePackageNames: [] };
  10. /**
  11. * @param scopes {string[]}
  12. */
  13. exports.listScopedPackages = (scopes, opts = defaultOpts) => {
  14. /** @type {string[]} */
  15. const scopedPackages = [];
  16. fs.readdirSync(nodeModulesPath)
  17. .filter(name => scopes.includes(name))
  18. .forEach((scope) => {
  19. fs.readdirSync(path.resolve(nodeModulesPath, scope))
  20. .filter(name => !name.startsWith('.'))
  21. .forEach((folderName) => {
  22. const packageJsonPath = path.resolve(
  23. nodeModulesPath,
  24. scope,
  25. folderName,
  26. 'package.json',
  27. );
  28. if (fs.existsSync(packageJsonPath)) {
  29. const { name } = require(packageJsonPath);
  30. if (!opts.ignorePackageNames.includes(name)) {
  31. scopedPackages.push(name);
  32. }
  33. }
  34. });
  35. });
  36. return scopedPackages;
  37. };
  38. /**
  39. * @param prefixes {string[]}
  40. */
  41. exports.listPrefixedPackages = (prefixes, opts = defaultOpts) => {
  42. /** @type {string[]} */
  43. const prefixedPackages = [];
  44. fs.readdirSync(nodeModulesPath)
  45. .filter(name => prefixes.some(prefix => name.startsWith(prefix)))
  46. .filter(name => !name.startsWith('.'))
  47. .forEach((folderName) => {
  48. const packageJsonPath = path.resolve(
  49. nodeModulesPath,
  50. folderName,
  51. 'package.json',
  52. );
  53. if (fs.existsSync(packageJsonPath)) {
  54. const { name } = require(packageJsonPath);
  55. if (!opts.ignorePackageNames.includes(name)) {
  56. prefixedPackages.push(name);
  57. }
  58. }
  59. });
  60. return prefixedPackages;
  61. };