Last active
March 29, 2016 02:34
-
-
Save ijse/ffa06369190ebfe4ac11 to your computer and use it in GitHub Desktop.
webpack-dev-middleware getFilenameFromUrl compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var url = require('url'); | |
var options = { | |
publicPath: '/test' | |
}; | |
var compiler = { | |
outputPath: '/' | |
}; | |
function pathJoin(a, b) { | |
return a == "/" ? "/" + b : (a||"") + "/" + b; | |
} | |
////The Original//// | |
function getFilenameFromUrl(url) { | |
// publicPrefix is the folder our bundle should be in | |
var localPrefix = options.publicPath || "/"; | |
if(url.indexOf(localPrefix) !== 0) { | |
if(/^(https?:)?\/\//.test(localPrefix)) { | |
localPrefix = "/" + localPrefix.replace(/^(https?:)?\/\/[^\/]+\//, ""); | |
// fast exit if another directory requested | |
if(url.indexOf(localPrefix) !== 0) return false; | |
} else return false; | |
} | |
// get filename from request | |
var filename = url.substr(localPrefix.length); | |
if(filename.indexOf("?") >= 0) { | |
filename = filename.substr(0, filename.indexOf("?")); | |
} | |
return filename ? pathJoin(compiler.outputPath, filename) : compiler.outputPath; | |
} | |
console.log(getFilenameFromUrl('http://test.domain/test/sample.js')); //output: false | |
console.log(getFilenameFromUrl('/test/sample.js')); //output: //ddd.js | |
console.log(); | |
/////My PR///// | |
var pathJoin = require('path').join; // why not use path.join? | |
var urlParse = require('url').parse; | |
function getFilenameFromUrl2(url) { | |
var filename; | |
// localPrefix is the folder our bundle should be in | |
var localPrefix = urlParse(options.publicPath || "/"); | |
var urlObject = urlParse(url); | |
if(localPrefix.hostname !== null && | |
urlObject.hostname !== null && | |
localPrefix.hostname !== urlObject.hostname) { | |
// publicPath has hostname and is not the same as request url's | |
return false; | |
} | |
// strip localPrefix from the start of url | |
if(urlObject.pathname.indexOf(localPrefix.pathname) === 0) { | |
filename = urlObject.pathname.substr(localPrefix.pathname.length); | |
} | |
// and if not match, use outputPath as filename | |
return filename ? pathJoin(compiler.outputPath, filename) : compiler.outputPath; | |
} | |
console.log(getFilenameFromUrl2('http://test.domain/test/sample.js')); //output: /sample.js | |
console.log(getFilenameFromUrl2('/test/sample.js')); //output: /sample.js |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment