Skip to content

Instantly share code, notes, and snippets.

Last active April 9, 2018 21:54
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save aesteve/883e0fd33390451cb8eb to your computer and use it in GitHub Desktop.
Save aesteve/883e0fd33390451cb8eb to your computer and use it in GitHub Desktop.
Transforming JSX with nashorn
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import jdk.nashorn.api.scripting.JSObject;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
public class Test {
public static void main(String... args) throws Exception {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine nashorn = mgr.getEngineByName("nashorn");
nashorn.eval("var process = {env:{}}"); // node-modules expect that
nashorn.eval("var global = this;"); // react expects that
JSObject jsxTransformer = (JSObject) nashorn.eval("JSXTransformer");
Invocable invocable = (Invocable) nashorn;
String componentName = "Component";
ScriptObjectMirror jsxMirror = (ScriptObjectMirror) invocable.invokeMethod(jsxTransformer, "transform", getCodeFromFile(componentName + ".jsx"));
String code = (String) jsxMirror.getMember("code");
writeScriptToPath(code, componentName + ".js");
// System.out.println(nashorn.eval("React.renderToString(React.createFactory(require('Component'))());"));
private static Reader getScript(String name) {
return new InputStreamReader(Test.class.getClassLoader().getResourceAsStream(name));
private static String getCodeFromFile(String name) throws Exception {
return new String(Files.readAllBytes(getPath(name)));
private static Path getPath(String name) throws Exception {
return Paths.get(ClassLoader.getSystemResource(name).toURI());
private static void writeScriptToPath(String content, String path) throws Exception {
Files.write(Paths.get(path), content.getBytes());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment