From e2d54ef8dd14ece19503f9931331623361e6a0be Mon Sep 17 00:00:00 2001 From: bbtfr Date: Fri, 6 May 2016 19:13:58 +0800 Subject: [PATCH] add alias feature to rewrite urls --- lib/loader.js | 12 ++++++++++++ test/aliasTest.js | 30 ++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 test/aliasTest.js diff --git a/lib/loader.js b/lib/loader.js index 8698160e..388508ea 100644 --- a/lib/loader.js +++ b/lib/loader.js @@ -70,6 +70,18 @@ module.exports = function(content, map) { var idx = +match[1]; var urlItem = result.urlItems[idx]; var url = urlItem.url; + var loaderOptions = this.options.cssLoader; + if (loaderOptions && loaderOptions.alias) { + var alias = loaderOptions.alias; + Object.keys(alias).forEach(function(aliasName) { + var aliasValue = alias[aliasName]; + var onlyModule = /\$$/.test(aliasName); + if (onlyModule) aliasName = aliasName.substr(0, aliasName.length - 1); + if ((!onlyModule && url.indexOf(aliasName + "/") === 0) || url === aliasName) { + url = aliasValue + url.substr(aliasName.length); + } + }); + } idx = url.indexOf("?#"); if(idx < 0) idx = url.indexOf("#"); var urlRequest; diff --git a/test/aliasTest.js b/test/aliasTest.js new file mode 100644 index 00000000..6fdbd2d2 --- /dev/null +++ b/test/aliasTest.js @@ -0,0 +1,30 @@ +/*globals describe */ + +var test = require("./helpers").test; + +describe("alias", function() { + var css = ".className { background: url(./path/to/file.png); }"; + var exports = { + without: [ + [1, ".className { background: url({./path/to/file.png}); }", ""] + ], + onlyModule: [ + [1, ".className { background: url({module/file.png}); }", ""] + ], + exactMatch: [ + [1, ".className { background: url({module/file.png}); }", ""] + ], + notExactMatch: [ + [1, ".className { background: url({./path/to/file.png}); }", ""] + ] + }; + + function aliasOptions(alias) { + return { options: { context: "", cssLoader: { alias: alias }}} + } + + test("without", css, exports.without); + test("onlyModule", css, exports.onlyModule, aliasOptions({ "./path/to": "module" })); + test("exactMatch", css, exports.exactMatch, aliasOptions({ "./path/to/file.png$": "module/file.png" })); + test("notExactMatch", css, exports.notExactMatch, aliasOptions({ "./path/to/file.jpg$": "module/file.jpg" })); +});