Skip to content

Add support for srcset #55

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 25, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,15 @@ Exports HTML as string. HTML is minimized when the compiler demands.

By default every local `<img src="image.png">` is required (`require("./image.png")`). You may need to specify loaders for images in your configuration (recommended `file-loader` or `url-loader`).

You can specify which tag-attribute combination should be processed by this loader via the query parameter `attrs`. Pass an array or a space-separated list of `<tag>:<attribute>` combinations. (Default: `attrs=img:src`)
Also every `<img srcset="..."`> is converted to `require` statements. For example
``` html
<img src="image.jpg" srcset="image.jpg 1x, [email protected] 2x">
```
is converted to
``` javascript
"<img src=\"" + require("./image.jpg") + "\" srcset=\"" + require("./image.jpg") + " 1x," + require("./[email protected]") + " 2x \">"
```
You can specify which tag-attribute combination should be processed by this loader via the query parameter `attrs`. Pass an array or a space-separated list of `<tag>:<attribute>` combinations. (Default: `attrs=[img:src, img:srcset]`)

To completely disable tag-attribute processing (for instance, if you're handling image loading on the client side) you can pass in `attrs=false`.

Expand Down
62 changes: 49 additions & 13 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ function getLoaderConfig(context) {
module.exports = function(content) {
this.cacheable && this.cacheable();
var config = getLoaderConfig(this);
var attributes = ["img:src"];
var attributes = ["img:src", "img:srcset"];
if(config.attrs !== undefined) {
if(typeof config.attrs === "string")
attributes = config.attrs.split(" ");
Expand All @@ -38,27 +38,56 @@ module.exports = function(content) {
throw new Error("Invalid value to config parameter attrs");
}
var root = config.root;
var links = attrParse(content, function(tag, attr) {
var rawLinks = attrParse(content, function(tag, attr) {
return attributes.indexOf(tag + ":" + attr) >= 0;
});
var links = [];
rawLinks.forEach(function (link) {
var length = link.length;
var start = link.start;
var valueList = link.value.split(",");
valueList.forEach(function (newLink) {
var trimmed = newLink.trim();
var cLength = newLink.length;
var spacePos = trimmed.indexOf(" ");
var spaceStart = newLink.indexOf(trimmed);
var len = cLength+ spaceStart;
if (-1 != spacePos) {
len = spacePos + spaceStart;
trimmed = trimmed.substring(0,spacePos);
}
links.push({start: start, length: len , value: trimmed});
start += cLength+1;
});
});
links.reverse();
var data = {};
content = [content];
links.forEach(function(link) {
if(!loaderUtils.isUrlRequest(link.value, root)) return;

var uri = url.parse(link.value);
if (uri.hash !== null && uri.hash !== undefined) {
uri.hash = null;
link.value = uri.format();
link.length = link.value.length;
}
var newValue = link.value.split(",");
var newValue = newValue.map(function (value) {
var valueArray = value.trim().split(" ");
var obj = {
value: valueArray.shift(),
additional: valueArray,
};
if(!loaderUtils.isUrlRequest(obj.value, root)) return;
var uri = url.parse(obj.value);
if (uri.hash !== null && uri.hash !== undefined) {
obj.hash = uri.hash;
uri.hash = null;
obj.value = uri.format();
}
return obj;
});

do {
var ident = randomIdent();
} while(data[ident]);
data[ident] = link.value;
data[ident] = newValue;
var x = content.pop();


content.push(x.substr(link.start + link.length));
content.push(ident);
content.push(x.substr(0, link.start));
Expand Down Expand Up @@ -95,9 +124,16 @@ module.exports = function(content) {
} else {
content = JSON.stringify(content);
}

return "module.exports = " + content.replace(/xxxHTMLLINKxxx[0-9\.]+xxx/g, function(match) {
if(!data[match]) return match;
return '" + require(' + JSON.stringify(loaderUtils.urlToRequest(data[match], root)) + ') + "';
return data[match].reduce(function (pV,cV, index, array) {

var hash = cV.hash || "";
var additional = cV.additional.length != 0 ? " " + cV.additional.join(" ") : "";
if (index != array.length -1) {
additional += ",";
}
return pV + '" + require(' + JSON.stringify(loaderUtils.urlToRequest(cV.value, root)) + ') + "' + hash + additional;
},"");
}) + ";";
}
29 changes: 25 additions & 4 deletions test/loaderTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,27 @@ describe("loader", function() {
'module.exports = "Text <script src=\\"" + require("./script.js") + "\\"><img src=\\"" + require("./image.png") + "\\">";'
);
});
it("should handle srcset-attrubute by default", function ()
{
loader.call({
},'Text <img srcset="image.png 1x">').should.be.eql(
'module.exports = "Text <img srcset=\\"" + require("./image.png") + " 1x\\">";'
)
});
it("should handle srcset-attrubute with comma seperated list", function ()
{
loader.call({
},'Text <img srcset="image.png 1x,[email protected] 2x">').should.be.eql(
'module.exports = "Text <img srcset=\\"" + require("./image.png") + " 1x,\" + require("./[email protected]") + " 2x\\">";'
)
});
it("should handle srcset-attrubute with comma seperated list, independend of spaces in list", function ()
{
loader.call({
},'Text <img srcset="image.png 1x, [email protected] 2x">').should.be.eql(
'module.exports = "Text <img srcset=\\"" + require("./image.png") + " 1x,\" + require("./[email protected]") + " 2x\\">";'
)
});
it("should not make bad things with templates", function() {
loader.call({}, '<h3>#{number} {customer}</h3>\n<p> {title} </p>').should.be.eql(
'module.exports = "<h3>#{number} {customer}</h3>\\n<p> {title} </p>";'
Expand All @@ -38,31 +59,31 @@ describe("loader", function() {
loader.call({
minimize: true
}, '<!-- comment --><h3 customAttr="">#{number} {customer}</h3>\n<p> {title} </p>\n\t <!-- comment --> <img src="image.png" />').should.be.eql(
'module.exports = "<h3 customattr=\\"\\">#{number} {customer}</h3> <p> {title} </p> <img src=\\"\" + require("./image.png") + "\\\"/>";'
'module.exports = "<h3 customattr=\\"\\">#{number} {customer}</h3> <p> {title} </p> <img src=\" + require("./image.png") + \" />";'
);
});
// https://github.com/webpack/webpack/issues/752
it("should not remove attributes by default", function() {
loader.call({
minimize: true
}, '<input type="text" />').should.be.eql(
'module.exports = "<input type=\\"text\\"/>";'
'module.exports = "<input type=text />";'
);
});
it("should preserve comments", function() {
loader.call({
minimize: true,
query: "?-removeComments"
}, '<!-- comment --><h3 customAttr="">#{number} {customer}</h3><p>{title}</p><!-- comment --><img src="image.png" />').should.be.eql(
'module.exports = "<!-- comment --><h3 customattr=\\"\\">#{number} {customer}</h3><p>{title}</p><!-- comment --><img src=\\"\" + require("./image.png") + "\\\"/>";'
'module.exports = "<!-- comment --><h3 customattr=\\"\\">#{number} {customer}</h3><p>{title}</p><!-- comment --><img src=\" + require("./image.png") + \" />";'
);
});
it("should treat attributes as case sensitive", function() {
loader.call({
minimize: true,
query: "?caseSensitive"
}, '<!-- comment --><h3 customAttr="">#{number} {customer}</h3><p>{title}</p><!-- comment --><img src="image.png" />').should.be.eql(
'module.exports = "<h3 customAttr=\\"\\">#{number} {customer}</h3><p>{title}</p><img src=\\"\" + require("./image.png") + "\\\"/>";'
'module.exports = "<h3 customAttr=\\"\\">#{number} {customer}</h3><p>{title}</p><img src=\" + require("./image.png") + \" />";'
);
});
it("should accept complex options via a webpack config property", function() {
Expand Down