I need help getting CommonJS working on Java 7 and Rhino 1.7R3.
Rhino 1.7R3 supports CommonJS modules:
And Java 7 comes bundled with Rhino 1.7R3. Unfortunately, Java 7's Rhino is a modified version, and it does not include the org.mozilla.javascript.commonjs
package:
I would like to use Rhino 1.7R3's support for CommonJS through the javax.script
API as follows:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
engine.put("markdown", markdown);
engine.eval("var html = require('./Markdown.Sanitizer').getSanitizingConverter().makeHtml(markdown);");
return (String) engine.get("html");
(I verified through the ScriptEngineManager
that I am indeed using the Rhino 1.7R3 engine.) I thought that perhaps I could just add the following dependency to the classpath
<dependency>
<groupId>org.mozilla</groupId>
<artifactId>rhino</artifactId>
<version>1.7R3</version>
</dependency>
and CommonJS—specifically, require()
—would start working. But it doesn't. When I try to use require()
I get
Caused by: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "require" is not defined. (<Unknown source>#2)
at sun.org.mozilla.javascript.internal.ScriptRuntime.constructError(ScriptRuntime.java:3773)
at sun.org.mozilla.javascript.internal.ScriptRuntime.constructError(ScriptRuntime.java:3751)
at sun.org.mozilla.javascript.internal.ScriptRuntime.notFoundError(ScriptRuntime.java:3836)
How do I get Java 7 to work with the full version of Rhino 1.7R3 so I can get CommonJS support?
EDIT: I found the following question, which deals with exactly the same topic:
Sanity check: Rhino does not have a require function, right?
The respondent suggests that maybe it's possible to replace the limited Rhino 1.7R3 with the CommonJS Rhino 1.7R3, but doesn't say how one might do that. That's what I'm asking about here.