Skip to content

Commit

Permalink
Revert "remove css"
Browse files Browse the repository at this point in the history
This reverts commit ad4780c.
  • Loading branch information
petehunt committed Oct 6, 2013
1 parent ad4780c commit 76dfd3f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
40 changes: 40 additions & 0 deletions index.js
@@ -1,7 +1,41 @@
var fs = require('fs');
var mimer = require('mimer');
var sha1 = require('sha1');
var through = require('through');

function insertRequiresIntoCSS(data) {
var re = /require\(["'](.*?)["']\)/;
var pieces = data.split(re);
return pieces.map(function(piece, index) {
var isRequire = index % 2 === 1;
if (!isRequire) {
return JSON.stringify(piece);
} else {
return '"url(" + require(' + JSON.stringify(piece) + ') + ")"';
}
}).join(' + ');
}

function transformCSS(data) {
var code = '';
var nodeID = '__staticify_style__' + sha1(data);
code += 'var nodeID = ' + JSON.stringify(nodeID) + ';\n';
code += 'var code = ' + insertRequiresIntoCSS(data) + ';\n';
code += 'if (typeof window === \'undefined\') {\n';
code += ' var g = eval(\'global\');\n'; // bypass browserify global insertion
code += ' if (!g.__staticify_css) {\n';
code += ' g.__staticify_css = [];\n';
code += ' }\n';
code += ' g.__staticify_css.push({nodeID: nodeID, code: code});\n';
code += '} else if (!document.getElementById(nodeID)) {\n';
code += ' var node = document.createElement(\'style\');\n';
code += ' node.setAttribute(\'id\', nodeID);\n';
code += ' node.innerHTML = code;\n';
code += ' document.head.appendChild(node);\n';
code += '}\n';
return code;
}

function transformImage(data, filename) {
var uri = 'data:' + mimer(filename) + ';base64,' + data;
return 'module.exports = ' + JSON.stringify(uri) + ';\n';
Expand All @@ -20,6 +54,10 @@ function isImage(filename) {
return hasExt(filename, ['.png', '.jpg', '.gif']);
}

function isCSS(filename) {
return hasExt(filename, ['.css', '.sass', '.scss', '.less']);
}

function transformer(func, args) {
var buf = '';
return through(
Expand Down Expand Up @@ -58,6 +96,8 @@ module.exports = function(filename) {
return guardWrites(
fs.createReadStream(filename, {encoding: 'base64'})
.pipe(transformer(transformImage, [filename])))
} else if (isCSS(filename)) {
return transformer(transformCSS, [filename]);
} else {
return through();
}
Expand Down
3 changes: 2 additions & 1 deletion package.json
Expand Up @@ -8,7 +8,8 @@
},
"dependencies": {
"through": "~2.3.4",
"mimer": "*"
"mimer": "*",
"sha1": "*"
},
"peerDependencies": {
"browserify": "2.x.x"
Expand Down

0 comments on commit 76dfd3f

Please sign in to comment.