Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run babel.transform for react with Nashorn?

I am trying to use babel.transform instead of JSXTranformer for react.

...
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine nashorn = mgr.getEngineByName("nashorn");
nashorn.eval("var process = {env:{}}"); // node-modules expect that
nashorn.eval(getScript("com/facebook/babel/jvm-npm.js"));
babel = (JSObject) nashorn.eval("require('babel');");
...

Babel and babel-core are installed as global node modules, and I've got an error:

Testsuite: com.my.app.BabelTransformerTest
Cannot find module ./lib/api/node.js
Cannot load module babel-core LOAD_ERROR
Cannot load module babel LOAD_ERROR
Cannot load module babel-core LOAD_ERROR
Cannot load module babel LOAD_ERROR
Cannot find module ./lib/api/node.js
Cannot load module babel-core LOAD_ERROR
Cannot load module babel LOAD_ERROR

The ./lib/api/node.js is there in the C:\Users\***\AppData\Roaming\npm\node_modules

I heard that it is possible to run babel.transform from Nashorn?

Maybe there is the way to load only certain module of babel as a JavaScript file?

like image 496
Alexander Arutinyants Avatar asked Sep 18 '15 14:09

Alexander Arutinyants


People also ask

How do you use Babel standalone?

Use it via UNPKG: https://unpkg.com/@babel/standalone/babel.min.js. This is a simple way to embed it on a webpage without having to do any other setup. Install via NPM: npm install --save @babel/standalone.

Does Babel need node?

If you've been active as a Node. js developer, or even dabbled in front-end libraries like React or Vue. js, then there's no doubt that you've likely run across Babel.


1 Answers

I have got it working with Babel Standalone in jdk1.8.0_45 with the following script:

FileReader babelScript = new FileReader("babel.js");
ScriptEngine engine = new ScriptEngineManager().getEngineByMimeType("text/javascript");

SimpleBindings bindings = new SimpleBindings();
engine.eval(babelScript, bindings);

bindings.put("input", "<Component />");
Object output = engine.eval("Babel.transform(input, { presets: ['react'] }).code", bindings);
System.out.println(output);

Which returns:

React.createElement(Component, null);

The es2015 preset works as well.

like image 117
Joel Avatar answered Sep 21 '22 10:09

Joel