requirepaths.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. Copyright 2014 Google LLC
  3. Use of this source code is governed by the MIT License, available in this package's LICENSE file
  4. or at http://opensource.org/licenses/MIT.
  5. */
  6. const path = require('path');
  7. function resolvePaths({ filepath }, paths) {
  8. if (!paths) {
  9. return [];
  10. }
  11. return paths.slice(0).map((p) => path.resolve(filepath, p));
  12. }
  13. function requirePaths(parentModule, opts) {
  14. const result = {
  15. before: [],
  16. after: [],
  17. };
  18. if (!parentModule) {
  19. return result;
  20. }
  21. if (Array.isArray(opts)) {
  22. result.before = resolvePaths(parentModule, opts);
  23. } else {
  24. result.before = resolvePaths(parentModule, opts.before);
  25. result.after = resolvePaths(parentModule, opts.after);
  26. }
  27. return result;
  28. }
  29. exports.before = function before(targetPath, parentModule, opts) {
  30. const resolvedPaths = requirePaths(parentModule, opts);
  31. return (
  32. `module.paths = ${JSON.stringify(resolvedPaths.before)}.concat(module.paths)` +
  33. `.concat(${JSON.stringify(resolvedPaths.after)}); `
  34. );
  35. };
  36. exports.after = function after() {
  37. return '';
  38. };