Skip to content

Instantly share code, notes, and snippets.

@Innei
Last active April 18, 2022 09:18
Show Gist options
  • Save Innei/b8619890f4947a40d80601da9c3b5bcc to your computer and use it in GitHub Desktop.
Save Innei/b8619890f4947a40d80601da9c3b5bcc to your computer and use it in GitHub Desktop.
rn-style-to-css
// @ts-check
import { FontSize, FontWeight, Color, LineHeight } from './styles';
const camelToSnakeCase = (str) =>
str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
const StyleSheet = {
create(a) {
return a;
},
};
const styles = StyleSheet.create({
container: {
paddingTop: 12,
},
});
let css = '.root * { display: flex; flex-direction: column;}\n\n';
Object.entries(styles).forEach(([k, v]) => {
css +=
`.${k} {
${Object.entries(v)
.map(([k, v]) => {
let value = v;
let key: string | string[] = k;
if (typeof key === 'string') {
const lowerKey = key.toLowerCase();
if (lowerKey.endsWith('horizontal')) {
const prefix = lowerKey.replace('horizontal', '');
key = [prefix + '-' + 'left', prefix + '-' + 'right'];
} else if (lowerKey.endsWith('vertical')) {
const prefix = lowerKey.replace('vertical', '');
key = [prefix + '-' + 'top', prefix + '-' + 'bottom'];
}
}
const needAddPx = [
'fontsize',
'lineheight',
'top',
'bottom',
'right',
'height',
'width',
'left',
'size',
'margin',
'padding',
'radius',
].some((key) => k.toLowerCase().includes(key) && typeof value === 'number');
if (key === 'transform') {
// TODO
value = (value as any as any[])
.map((obj) => {
return Object.keys(obj)
.map((key) => {
const unit = key == 'rotate' ? 'deg' : 'px';
return `${key}(${obj[key]}${unit})`;
})
.join(', ');
})
.join(' ');
}
// @ts-ignore
return Array.isArray(key)
? key
.map(
(k) => `${camelToSnakeCase(k)}: ${value}${needAddPx ? 'px' : ''};`
)
.join('\n')
: `${camelToSnakeCase(key)}: ${value}${needAddPx ? 'px' : ''};`;
})
.join('\n')}
}
`.trim() + '\n\n';
});
console.log(css);
// copy to clipboard macos
require('child_process').execSync('pbcopy', { input: css });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment