graalvm js 内置commonjs 模式试用
昨天有大概介绍过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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2019-08-31 haproxy 2.0 dataplaneapi docker 镜像
2019-08-31 haproxy2.0 dataplaneapi 简单说明
2019-08-31 使用jenkins exporter 监控jenkins 构建任务
2018-08-31 openresty 使用cuid 类库生成短链接id
2018-08-31 比jsonpath 更方便的json 数据查询JMESPath 使用
2018-08-31 streamsets 集成 rabbitmq 以及benthos stream 处理框架
2014-08-31 asp.net MVC 使用wifidog 协议实现wifi认证