Nova
Transpiler

JSX to PHP Transpiler

Summary

The JSX to PHP Transpiler allows us to build the component library using React components, which are then transpiled to PHP templates for rendering in a WordPress context.

Run the transpiler

From the root of pmc-nova/style-guide/ run

npm run transpile

This will generate the template.php in each component's directory.

⚠️

Manual changes made to template.php files will be overwritten when the transpiler runs (including every build). See below for further guidance.

What gets transpiled

It's important to note that the transpiler only transpiles what's in the return statement of the corresponding React component. This means a few important things:

  • The schema.json dictates the values used in the return, not the component props.
  • Any JSX outside of the return will not be transpiled.
  • Any variables defined outside of the return must be set in the schema.json and populated either in schema.json, defaults.json, or the component's model, otherwise warnings will be thrown (which often leads to errors and other unexpected behaviour).

My JSX isn't transpiling to the PHP I want/expect

Without getting into the nuances, there are some language features and patterns that just don't make the mental/logical leap from JSX to PHP smoothly. In these situations, you may need to update the transpiler to add proper support, or rework the JSX. The transpiler will output warnings when unsupported syntax is encountered, so be sure to check the output if the result doesn't match expectations.

We strive to support as much as possible, and while it can seem scary, getting started with understanding the inner-workings of the transpiler is very approachable.

You may notice some odd PHP syntax, such as excessive parenthesis or null-coalescence operators that seem unnecessary. These are present because the transpiler has limited context when parsing a specific node within the AST, and without this superfluous syntax, invalid PHP would result, or logic errors could be introduced.

How it works

When ran, the transpiler loops through the component library, reading the index.js file for every component.

The code is then passed into Acorn (opens in a new tab) to be parsed as an Abstract Syntax Tree (ast), which is traversed over, returning strings representing the JSX nodes as "close-enough" PHP versions.

We recommend pasting component JSX into AST Explorer (opens in a new tab) to visualize how the AST tree is parsed.