require.js在rhino上运行良好。最近,我在一个项目中使用了它。
- 您必须确保使用r.js(不是require.js),犀牛的require.js的修改版本。
- 您必须扩展
ScritableObject
类才能实现load
和print
运行。调用时require(["a"])
,将调用此类中的load函数,您可以调整此函数以从任何位置加载js文件。在以下示例中,我从加载classpath
。 - 您必须
arguments
在sharedscope中定义属性,如下面的示例代码所示 - (可选)您可以使用配置子路径
require.config
,以指定classpath内js文件所在的子目录。
JsRuntime支持
public class JsRuntimeSupport extends scriptableObject { private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(JsRuntimeSupport.class); private static final boolean silent = false; @Override public String getClassName() { return "test"; } public static void print(Context cx, scriptable thisObj, Object[] args, Function funObj) { if (silent) return; for (int i = 0; i < args.length; i++) logger.info(Context.toString(args[i])); } public static void load(Context cx, scriptable thisObj, Object[] args, Function funObj) throws FileNotFoundException, IOException { JsRuntimeSupport shell = (JsRuntimeSupport) getTopLevelScope(thisObj); for (int i = 0; i < args.length; i++) { logger.info("Loading file " + Context.toString(args[i])); shell.processSource(cx, Context.toString(args[i])); } } private void processSource(Context cx, String filename) throws FileNotFoundException, IOException { cx.evaluateReader(this, new InputStreamReader(getInputStream(filename)), filename, 1, null); } private InputStream getInputStream(String file) throws IOException { return new ClassPathResource(file).getInputStream(); }}样例代码
public class RJsDemo { @Test public void simpleRhinoTest() throws FileNotFoundException, IOException { Context cx = Context.enter(); final JsRuntimeSupport browserSupport = new JsRuntimeSupport(); final scriptableObject sharedScope = cx.initStandardObjects(browserSupport, true); String[] names = { "print", "load" }; sharedScope.defineFunctionProperties(names, sharedScope.getClass(), scriptableObject.DONTENUM); scriptable argsObj = cx.newArray(sharedScope, new Object[] {}); sharedScope.defineProperty("arguments", argsObj, scriptableObject.DONTENUM); cx.evaluateReader(sharedScope, new FileReader("./r.js"), "require", 1, null); cx.evaluateReader(sharedScope, new FileReader("./loader.js"), "loader", 1, null); Context.exit(); }}loader.js
require.config({ baseUrl: "js/app"});require (["a", "b"], function(a, b) { print('modules loaded');});js/app目录应该在您的类路径中。



