Skip to content

Instantly share code, notes, and snippets.

@lljxx1
Last active January 20, 2021 06:06
Show Gist options
  • Save lljxx1/5d44d918fb8c8f338d6397d6ff61a254 to your computer and use it in GitHub Desktop.
Save lljxx1/5d44d918fb8c8f338d6397d6ff61a254 to your computer and use it in GitHub Desktop.
根据font size比率,批量转换css中的rem单位
var css = require('css');
var fs = require('fs');
var sourceFile = 'style.css';
var content = fs.readFileSync('./' + sourceFile, 'utf-8');
var obj = css.parse(content);
var rawFontSize = 50;
var toFontSize = 20;
function transformRem(defin, declaration) {
var paires = defin.split(" ");
return paires.map(raw => {
if(raw === 'auto') return raw
var rawValue = parseFloat(raw.replace('rem', ''));
var newValue = (rawFontSize / toFontSize) * rawValue
var finalValue = newValue.toFixed(3)
if(isNaN(finalValue)) return 0;
console.log('rawValue', rawValue, 'newValue', newValue)
return [finalValue, 'rem'].join('')
}).join(" ")
}
obj.stylesheet.rules.map(_ => {
if(_.type == 'rule') {
_.declarations.map(declaration => {
if(declaration.value && declaration.value.indexOf('rem') > -1) {
if(declaration.property === 'padding') {
console.log(declaration)
}
declaration.value = transformRem(declaration.value, declaration);
}
return declaration;
})
}
return _;
})
var newContent = css.stringify(obj);
fs.writeFileSync('new_' + sourceFile, newContent)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment