Melange

Ensure that you have set up a Melange project beforehand. If you haven’t done so yet, refer to the Melange getting started documentation.

This guide assumes that you’ll use opam and dune.

Install

opam install styled-ppx

Packages available

  • styled-ppx is the ppx to transform [%styled.div ""] and [%cx ""]
  • styled-ppx.melange is library with the runtime

Usage

  1. Add styled-ppx under dune’s preprocess pps
  2. Add styled-ppx.melange under libraries

in a dune library with (modes melange):

(library
  (name ...)
  (modes melange)
  (libraries
+   styled-ppx.melange
    reason-react)
  (preprocess
    (pps
+     styled-ppx
      melange.ppx
      reason-react-ppx)))

or in the melange.emit stanza:

(melange.emit
  (libraries
+   styled-ppx.melange
    reason-react)
  (preprocess
    (pps
+     styled-ppx
      melange.ppx
      reason-react-ppx)))

Note: reason-react and reason-react-ppx are optional, and only needed if you use styled components ([%styled.div {||}]).

Example

/* This is a ReasonReact module with those styles encoded as a unique className */
module Link = [%styled.a (~color=CSS.hex("4299E1")) => {|
  font-size: 1.875rem;
  line-height: 1.5;
  text-decoration: none;
  margin: 0px;
  padding: 10px 0px;
  color: $(color);
|}];
 
/* This is a unique className generated by the styles */
let layout = [%cx {|
  display: flex;
  width: 100%;
  height: 100%;
  justify-content: center;
  align-items: center
|}];
 
/* Later in a component */
<div className=layout>
  <Link
    color={CSS.hex("333333")}
    href="https://sancho.dev"
    rel="noopener noreferrer">
    {React.string("sancho.dev")}
  </Link>
</div>;