0.3.0 • Published 6 years ago

css-to-rn.macro v0.3.0

Weekly downloads
12
License
MIT
Repository
github
Last release
6 years ago

css-to-rn.macro NPM version Build Status Greenkeeper badge

Convert CSS to React Native style sheet at build time with babel macros, using css-to-react-native-transform.

  • A lightweight way to write CSS for React Native
  • Use CSS to write React Native styles without take startup time for parse in JS runtime
  • Support editor plugin that detect css template literal like vscode-styled-components

Installation

$ npm install --save-dev css-to-rn.macro

You'll also need to install and configure babel-plugin-macros if you haven't already.

Example

Input:

import { StyleSheet } from 'react-native'
import css from 'css-to-rn.macro'

const styles = StyleSheet.create(
  css`
    .container {
      flex: 1;
      justify-content: center;
      align-items: center;
    }
  `,
)

Output:

import { StyleSheet } from 'react-native'

const styles = StyleSheet.create({
  container: {
    flexGrow: 1,
    flexShrink: 1,
    flexBasis: 0,
    justifyContent: 'center',
    alignItems: 'center',
  },
})

Media Queries support

The css-to-react-native-transform allow parsing the CSS Media Queries, and you can use it with react-native-css-media-query-processor

This is example for change styles with platform:

import { StyleSheet } from 'react-native'
import css, { parseMedia } from 'css-to-rn.macro'

const styles = StyleSheet.create(
  parseMedia(
    css`
      .container {
        flex: 1;
        justify-content: center;
        align-items: center;
      }
      @media not android {
        .container {
          background-color: #ccc;
        }
      }
    `,
    {
      /* match object of react-native-css-media-query-processor */
    },
  ),
)

Limitations

Unable to parse unknown values in CSS template literal, for example:

const height = Math.random() * 100
css`
  .container {
    height: ${height};
  }
`

Due to the height is random number, so it's unknown value at build time.

It will just fallback to css-to-react-native-transform with a warning, but you can still use this macro.

License

MIT