昨天有大概介紹過graalvm 對於commonjs 的支持,以下是簡單的試用說明
環境准備
- pom.xml
依賴配置
<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>
- npm 代碼結構
使用yarn 管理的,添加了一個hashids 的包
- 代碼使用
Engine 對象定義,主要開啟了實驗特性
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