GetFilenameFromUrl.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. var pathJoin = require("./PathJoin");
  2. var querystring = require("querystring");
  3. var urlParse = require("url").parse;
  4. function getFilenameFromUrl(publicPath, outputPath, url) {
  5. var filename;
  6. // localPrefix is the folder our bundle should be in
  7. var localPrefix = urlParse(publicPath || "/", false, true);
  8. var urlObject = urlParse(url);
  9. // publicPath has the hostname that is not the same as request url's, should fail
  10. if(localPrefix.hostname !== null && urlObject.hostname !== null &&
  11. localPrefix.hostname !== urlObject.hostname) {
  12. return false;
  13. }
  14. // publicPath is not in url, so it should fail
  15. if(publicPath && localPrefix.hostname === urlObject.hostname && url.indexOf(publicPath) !== 0) {
  16. return false;
  17. }
  18. // strip localPrefix from the start of url
  19. if(urlObject.pathname.indexOf(localPrefix.pathname) === 0) {
  20. filename = urlObject.pathname.substr(localPrefix.pathname.length);
  21. }
  22. if(!urlObject.hostname && localPrefix.hostname &&
  23. url.indexOf(localPrefix.path) !== 0) {
  24. return false;
  25. }
  26. // and if not match, use outputPath as filename
  27. return querystring.unescape(filename ? pathJoin(outputPath, filename) : outputPath);
  28. }
  29. // support for multi-compiler configuration
  30. // see: https://github.com/webpack/webpack-dev-server/issues/641
  31. function getPaths(publicPath, compiler, url) {
  32. var compilers = compiler && compiler.compilers;
  33. if(Array.isArray(compilers)) {
  34. var compilerPublicPath;
  35. for(var i = 0; i < compilers.length; i++) {
  36. compilerPublicPath = compilers[i].options
  37. && compilers[i].options.output
  38. && compilers[i].options.output.publicPath;
  39. if(url.indexOf(compilerPublicPath) === 0) {
  40. return {
  41. publicPath: compilerPublicPath,
  42. outputPath: compilers[i].outputPath
  43. };
  44. }
  45. }
  46. }
  47. return {
  48. publicPath: publicPath,
  49. outputPath: compiler.outputPath
  50. };
  51. }
  52. module.exports = function(publicPath, compiler, url) {
  53. var paths = getPaths(publicPath, compiler, url);
  54. return getFilenameFromUrl(paths.publicPath, paths.outputPath, url);
  55. };