ES6 from Java, using Nashorn

Olivier olivier.lediouris at oracle.com
Mon Jan 8 16:33:57 UTC 2018


Hi experts,
I want to run ES6 scripts from Java, using Nashorn.
I have scripts involving 'let', 'const', my Java code is happy with it, 
I just need to use a property "nashorn.args" set to "--language=es6".

Now, I'd like to move forward, use imports and modules.
I have one script like this (modules.01.js):

function displayMessage() {
  console.log("Hello JS World!");
};

export default displayMessage;

I want to consume it from this (modules.consume.js):

import displayMessagefrom './modules.01';

displayMessage();

But this is where I have a question:
My engine.eval("load('./modules.consume.js');"); complains about the "import" statement.
In the transpiled version, it complains about the "require" statement.

I must be missing something... I attach my code, in case it's needed.

Any idea, pointer, comment, help, etc, most welcome,
Thank you!
- Olivier



-------------- next part --------------
package scripting;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import java.io.File;
import java.io.FileReader;
import java.util.List;
import java.util.stream.Collectors;

public class Executor {
	private final static String SCRIPT_TO_RUN = "es6" + File.separator + "out" + File.separator + "modules.consume.js"; // Transpiled
//private final static String SCRIPT_TO_RUN = "es6" + File.separator + "modules.consume.js"; // Not transpiled

	private final static String NASHORN_ARGS = "nashorn.args";
	private final static String ES_6 = "--language=es6";


	public static void main(String... args) throws Exception {

		System.out.println(String.format("Running from [%s]", System.getProperty("user.dir")));

		String script =  SCRIPT_TO_RUN;
		if (args.length > 0) {
			script = args[0];
		}

		System.setProperty(NASHORN_ARGS, ES_6);

		ScriptEngineManager factory = new ScriptEngineManager();
		List<ScriptEngineFactory> engineFactories = factory.getEngineFactories();
		System.out.println(String.format("%s factory(ies).", engineFactories.size()));
		engineFactories.stream().forEach(ef -> {
			System.out.println(String.format("%s (%s)",
					ef.getEngineName(),
					ef.getNames().stream().collect(Collectors.joining(", "))));
		});

		ScriptEngine engine = factory.getEngineByName("nashorn");
		FileReader reader = new FileReader(script);
		try {
			engine.eval(reader);
		} catch (Exception ex) {
			System.err.println("Ooops:" + ex.toString());
		} finally {
			reader.close();
		}
		// Another approach
		try {
			String command = String.format("load('%s');", script);
			System.out.println(String.format("Executing [%s]", command));
			engine.eval(command);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		engine.eval("print('Bye now.');");
	}
}


More information about the nashorn-dev mailing list