提交学习笔记专用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.3 KiB

  1. var path = require('path');
  2. var parse = path.parse || require('path-parse'); // eslint-disable-line global-require
  3. var driveLetterRegex = /^([A-Za-z]:)/;
  4. var uncPathRegex = /^\\\\/;
  5. var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) {
  6. var prefix = '/';
  7. if (driveLetterRegex.test(absoluteStart)) {
  8. prefix = '';
  9. } else if (uncPathRegex.test(absoluteStart)) {
  10. prefix = '\\\\';
  11. }
  12. var paths = [absoluteStart];
  13. var parsed = parse(absoluteStart);
  14. while (parsed.dir !== paths[paths.length - 1]) {
  15. paths.push(parsed.dir);
  16. parsed = parse(parsed.dir);
  17. }
  18. return paths.reduce(function (dirs, aPath) {
  19. return dirs.concat(modules.map(function (moduleDir) {
  20. return path.resolve(prefix, aPath, moduleDir);
  21. }));
  22. }, []);
  23. };
  24. module.exports = function nodeModulesPaths(start, opts, request) {
  25. var modules = opts && opts.moduleDirectory
  26. ? [].concat(opts.moduleDirectory)
  27. : ['node_modules'];
  28. if (opts && typeof opts.paths === 'function') {
  29. return opts.paths(
  30. request,
  31. start,
  32. function () { return getNodeModulesDirs(start, modules); },
  33. opts
  34. );
  35. }
  36. var dirs = getNodeModulesDirs(start, modules);
  37. return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
  38. };