webpack/lib/RequestShortener.js

56 lines
2.2 KiB
JavaScript
Raw Normal View History

2013-01-31 01:49:25 +08:00
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var path = require("path");
function RequestShortener(directory) {
var parentDirectory = path.dirname(directory);
2015-07-13 06:20:09 +08:00
if (/[\/\\]$/.test(directory)) directory = directory.substr(0, directory.length - 1);
if (directory) {
2013-07-11 05:20:07 +08:00
var currentDirectoryRegExp = directory.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
currentDirectoryRegExp = new RegExp("^" + currentDirectoryRegExp + "|(!)" + currentDirectoryRegExp, "g");
this.currentDirectoryRegExp = currentDirectoryRegExp;
}
2015-07-13 06:20:09 +08:00
if (/[\/\\]$/.test(parentDirectory)) parentDirectory = parentDirectory.substr(0, parentDirectory.length - 1);
if (parentDirectory && parentDirectory !== directory) {
2013-07-11 05:20:07 +08:00
var parentDirectoryRegExp = parentDirectory.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
parentDirectoryRegExp = new RegExp("^" + parentDirectoryRegExp + "|(!)" + parentDirectoryRegExp, "g");
this.parentDirectoryRegExp = parentDirectoryRegExp;
}
2015-07-13 06:20:09 +08:00
if (__dirname.length >= 2) {
2013-07-11 05:20:07 +08:00
var buildins = path.join(__dirname, "..");
2014-05-14 14:20:57 +08:00
var buildinsAsModule = currentDirectoryRegExp && currentDirectoryRegExp.test(buildins);
2013-07-11 05:20:07 +08:00
var buildinsRegExp = buildins.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
buildinsRegExp = new RegExp("^" + buildinsRegExp + "|(!)" + buildinsRegExp, "g");
this.buildinsAsModule = buildinsAsModule;
this.buildinsRegExp = buildinsRegExp;
}
2015-04-24 05:55:50 +08:00
this.nodeModulesRegExp = /\/node_modules\//g;
this.indexJsRegExp = /\/index.js(!|\?|\(query\))/g;
2013-01-31 01:49:25 +08:00
}
module.exports = RequestShortener;
RequestShortener.prototype.shorten = function(request) {
2015-07-13 06:20:09 +08:00
if (!request)
2013-01-31 01:49:25 +08:00
return request;
2015-07-13 06:20:09 +08:00
if (this.buildinsAsModule && this.buildinsRegExp)
2013-01-31 01:49:25 +08:00
request = request.replace(this.buildinsRegExp, "!(webpack)");
2015-07-13 06:20:09 +08:00
if (this.currentDirectoryRegExp)
2013-07-11 05:20:07 +08:00
request = request.replace(this.currentDirectoryRegExp, "!.");
2015-07-13 06:20:09 +08:00
if (this.parentDirectoryRegExp)
2013-07-11 05:20:07 +08:00
request = request.replace(this.parentDirectoryRegExp, "!..");
2015-07-13 06:20:09 +08:00
if (!this.buildinsAsModule && this.buildinsRegExp)
2013-01-31 01:49:25 +08:00
request = request.replace(this.buildinsRegExp, "!(webpack)");
request = request.replace(/\\/g, "/");
2015-04-24 05:55:50 +08:00
request = request.replace(this.nodeModulesRegExp, "/~/");
request = request.replace(this.indexJsRegExp, "$1");
2013-01-31 01:49:25 +08:00
return request.replace(/^!|!$/, "");
};