昨天有大概介绍过graalvm 对于commonjs 的支持,以下是简单的试用说明
<dependency>
<groupId>org.graalvm.truffle</groupId>
<artifactId>truffle-api</artifactId>
<version>20.2.0</version>
</dependency>
<dependency>
<groupId>org.graalvm.sdk</groupId>
<artifactId>graal-sdk</artifactId>
<version>20.2.0</version>
</dependency>
<dependency>
<groupId>org.graalvm.js</groupId>
<artifactId>js-scriptengine</artifactId>
<version>20.2.0</version>
</dependency>
<dependency>
<groupId>org.graalvm.js</groupId>
<artifactId>js</artifactId>
<version>20.2.0</version>
</dependency>
Engine engine = Engine.newBuilder().option("js.load-from-url","true").allowExperimentalOptions(true).build();
主要是关于commonjs 选项的配置,npm位置以及开启comomjs 处理
public static void commonjs(Engine engine){
Map<String, String> options = new HashMap<>();
options.put("js.commonjs-require-cwd", "src/main/resources/app");
options.put("js.commonjs-require", "true");
Context context = Context.newBuilder().allowAllAccess(true).options(options).allowHostClassLoading(true).allowIO(true).allowNativeAccess(true).engine(engine).build();
context.eval("js","const Hashids = require(‘hashids/cjs‘)\n" +
"const hashids = new Hashids()\n" +
" \n" +
"console.log(hashids.encode(222))");
?
}
有些npm build in的模块可能不能使用,这个可以通过hack 的方式解决(配置js.commonjs-core-modules-replacements参数),同时对于好多不支持的commonjs 模块我们可以基于browserify 提供的一些hacks,还是很不错的
https://github.com/graalvm/graaljs/blob/master/docs/user/NodeJSVSJavaScriptContext.md
https://github.com/browserify/browserify#usage
原文:https://www.cnblogs.com/rongfengliang/p/13589056.html