Skip to content

Instantly share code, notes, and snippets.

@kasuganosora
Created December 8, 2013 12:15
Show Gist options
  • Save kasuganosora/7856615 to your computer and use it in GitHub Desktop.
Save kasuganosora/7856615 to your computer and use it in GitHub Desktop.
提取响应式布局的某个分辨率生效的样式
var fs = require('fs');
var fileContent = fs.readFileSync("style.css", "utf8");
respond = {};
respond.regex = {
media: /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+\s*\}/gi,
keyframes: /@.*keyframes[^\{]+\{(?:[^\{\}]*\{[^\}\{]*\})+[^\}]+\}/gi,
urls: /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,
findStyles: /@media *([^\{]+)\{([\S\s]+?)$/,
only: /(only\s+)?([a-zA-Z]+)\s?/,
minw: /\([\s]*min\-width\s*:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/,
maxw: /\([\s]*max\-width\s*:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/,
styleBlock: /([^\{]+)\{([^\{\}]+?)\}/g
};
//屏幕宽度
var setScreenWidth = 1080;
var parse = require('css-parse');
var srcCssBlocks = fileContent.match(respond.regex.styleBlock);
var obj = parse(fileContent);
var styleArr = [];
var syleText = "";
for(var i = 0, l = obj.stylesheet.rules.length; i < l; i++){
var it = obj.stylesheet.rules[i];
if(it.media){
var minw = it.media.match(respond.regex.minw) && parseFloat(RegExp.$1) + (RegExp.$2 || "");
var maxw = it.media.match(respond.regex.maxw) && parseFloat(RegExp.$1) + (RegExp.$2 || "");
if(minw != null && maxw != null && parseFloat(minw) < setScreenWidth && parseFloat(maxw) > setScreenWidth){
styleArr.push(getCSSTexts(it.rules));
continue;
}
if(minw != null && parseFloat(minw) < setScreenWidth){
styleArr.push(getCSSTexts(it.rules));
continue;
}
if(maxw != null && parseFloat(maxw) > setScreenWidth){
styleArr.push(getCSSTexts(it.rules));
continue;
}
}else{
if(it.type == "charset"){
styleArr.push(charsetText(it));
continue;
}
if(it.type == "rule"){
styleArr.push(getCSSText(it));
continue;
}
}
}
syleText = styleArr.join("\n");
//保存文件
fs.writeFileSync("test1.css", syleText, {encoding:"utf8" });
function charsetText(rule){
if(rule.type != "charset"){
return false;
}
return "@" + rule.type + " " + rule.charset + ";";
}
function getCSSText(rule){
if(rule.type != "rule"){
return false;
}
var selectorText = rule.selectors.join(",");
var cssBody =[];
for(var j = 0, k = rule.declarations.length; j < k; j++){
var dec = rule.declarations[j];
if(dec.type != "declaration"){
continue;
}
cssBody.push(dec.property + ":" + dec.value);
}
return selectorText + "{" + cssBody.join(";") + "}";
}
function getCSSTexts(rules){
var cssTextArr = [];
for(var i =0, l = rules.length; i < l; i ++){
var r = rules[i];
css = getCSSText(r);
if(css == false){
continue;
}
cssTextArr.push(css);
}
return cssTextArr.join("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment