Skip to content

Commit

Permalink
Using media types instead of filename extension
Browse files Browse the repository at this point in the history
  • Loading branch information
trygve-lie committed Jan 23, 2013
1 parent 3fadd57 commit 1cd1265
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 2 deletions.
17 changes: 15 additions & 2 deletions lib/css-b64-images.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,20 @@ var fs = require('fs'),
/* Adapted from https://gist.github.com/2594980 */
imgRegex = /url\s?\(['"]?(.*?)(?=['"]?\))/gi,
absoluteUrlRegex = /^\//,
externalUrlRegex = /http/;
externalUrlRegex = /http/,
mediatypes = {
'eot' : 'application/vnd.ms-fontobject',
'gif' : 'image/gif',
'ico' : 'image/vnd.microsoft.icon',
'jpg' : 'image/jpeg',
'jpeg' : 'image/jpeg',
'otf' : 'application/x-font-opentype',
'png' : 'image/png',
'svg' : 'image/svg+xml',
'ttf' : 'application/x-font-ttf',
'webp' : 'image/webp',
'woff' : 'application/x-font-woff'
};

module.exports = {
fromFile: fromFile,
Expand Down Expand Up @@ -57,7 +70,7 @@ function replaceUrlByB64(imageUrl, imagePath, css, cb){
fs.readFile(imagePath, 'base64', function(err, img){
if(err) return cb(err, css);
var ext = imagePath.substr(imagePath.lastIndexOf('.') + 1);
var newCss = css.replace(imageUrl, 'data:image/' + ext + ';base64,' + img);
var newCss = css.replace(imageUrl, 'data:' + mediatypes[ext] + ';base64,' + img);
cb(null, newCss);
});
});
Expand Down
2 changes: 2 additions & 0 deletions test/css-b64-images-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,6 @@ function cssShouldBeCorrect(css){
css.should.include(".external {\n background: url('http");
css.should.include(".tooBig {\n background: url('../img");
css.should.include(".not-found {\n background: url('../img");

css.should.include(".mediatype {\n background: url('data:image/svg+xml;base64,");
}
4 changes: 4 additions & 0 deletions test/fixture/css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,7 @@
.not-found {
background: url('../img/nlabal.png');
}

.mediatype {
background: url('../img/dots.svg');
}
6 changes: 6 additions & 0 deletions test/fixture/img/dots.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 1cd1265

Please sign in to comment.