Skip to content

Commit 863c9d7

Browse files
committed
add alias feature to rewrite urls
1 parent b6acfec commit 863c9d7

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

lib/loader.js

+16
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,22 @@ module.exports = function(content, map) {
7171
var idx = +match[1];
7272
var urlItem = result.urlItems[idx];
7373
var url = urlItem.url;
74+
var loaderOptions = this.options.cssLoader;
75+
if (loaderOptions && loaderOptions.alias) {
76+
var alias = loaderOptions.alias;
77+
Object.keys(alias).forEach(function(aliasName) {
78+
var aliasValue = alias[aliasName];
79+
var onlyModule = /\$$/.test(aliasName);
80+
if (onlyModule) aliasName = aliasName.substr(0, aliasName.length - 1);
81+
if ((!onlyModule && url.indexOf(aliasName + "/") === 0) || url === aliasName) {
82+
if (typeof aliasValue === "function") {
83+
url = aliasValue(url);
84+
} else {
85+
url = aliasValue + url.substr(aliasName.length);
86+
}
87+
}
88+
});
89+
}
7490
idx = url.indexOf("?#");
7591
if(idx < 0) idx = url.indexOf("#");
7692
var urlRequest;

test/aliasTest.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*globals describe */
2+
3+
var test = require("./helpers").test;
4+
5+
describe("alias", function() {
6+
var css = ".className { background: url(./path/to/file.png); }";
7+
var exports = {
8+
without: [
9+
[1, ".className { background: url({./path/to/file.png}); }", ""]
10+
],
11+
onlyModule: [
12+
[1, ".className { background: url({module/file.png}); }", ""]
13+
],
14+
exactMatch: [
15+
[1, ".className { background: url({module/file.png}); }", ""]
16+
],
17+
notExactMatch: [
18+
[1, ".className { background: url({./path/to/file.png}); }", ""]
19+
],
20+
function: [
21+
[1, ".className { background: url({return/value}); }", ""]
22+
]
23+
};
24+
25+
function aliasOptions(alias) {
26+
return { options: { context: "", cssLoader: { alias: alias }}}
27+
}
28+
29+
test("without", css, exports.without);
30+
test("onlyModule", css, exports.onlyModule, aliasOptions({ "./path/to": "module" }));
31+
test("exactMatch", css, exports.exactMatch, aliasOptions({ "./path/to/file.png$": "module/file.png" }));
32+
test("notExactMatch", css, exports.notExactMatch, aliasOptions({ "./path/to/file.jpg$": "module/file.jpg" }));
33+
test("function", css, exports.function, aliasOptions({ "./path/to": function(urlRequest) { return "return/value" } }));
34+
});

0 commit comments

Comments
 (0)