简体   繁体   中英

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?

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.

You should just load babel.js directly and then evaluate babel.transform("...") . There shouldn't be any need to load anything from npm or node.

But, alas, you'll have to wait for the fix to JDK bug 8135190 to be released, as loading babel.js fails with a "method code too large" exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM