graalvm 是直接支持es6模块的,以前有写过基于require 模块模式的npm包加载处理(jvm-npm)以下是我们
基于rollup 转换comomjs 模块为es6 模块,方便的扩展java 的能力
场景说明
npm 包含了一个很不错的json-mask 包,但是我们希望java可以直接集成使用,所以我们希望使用java 的graalvm js 引擎处理
集成说明
因为graalvm直接支持es6模块,我们直接使用es6模块就可以了,但是因为json-mask 是commonjs 模块的,我们需要一种机制进行转换
rollup 是一个不错的选择
转换json-mask 为es6 模块
- 项目结构
├── mymask.js
├── package.json
├── rollup.config.js
└── yarn.lock
- package.json
{
"name": "p",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"devDependencies": {
"@babel/preset-env": "^7.11.0",
"@babel/core": "^7.11.4",
"@rollup/plugin-commonjs": "^15.0.0",
"@rollup/plugin-node-resolve": "^9.0.0",
"rollup": "^2.26.8",
"@rollup/plugin-babel": "^5.2.0"
},
"scripts": {
"demoapp": "rollup -c rollup.config.js "
},
"dependencies": {
"json-mask": "^1.0.1"
}
}
- rollup.config.js
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import { getBabelOutputPlugin } from '@rollup/plugin-babel';
export default {
input: 'mymask.js',
output: [{
dir: 'app',
format: 'es',
plugins: [getBabelOutputPlugin({ presets: ['@babel/preset-env'] })]
}],
plugins: [resolve(), commonjs()]
};
- mymask.js
const mask = require("json-mask")
module.exports = {
maskfn: function (datas, fields) {
return mask(datas, fields)
}
}
java 集成
- 项目结构
- 代码集成
Engine engine = Engine.newBuilder().option("js.load-from-url","true").allowExperimentalOptions(true).build();
public static void es6Rollup(Engine engine) throws IOException {
Context context = Context.newBuilder().allowAllAccess(true).allowHostClassLoading(true).allowIO(true).allowNativeAccess(true).engine(engine).build();
Source mysource = Source.newBuilder("js","import mymask from "src/main/resources/mymask.js"
" +
"var fields = 'url,object(content,attachments/url)';
" +
"var originalObj = {
" +
" id: 'z12gtjhq3qn2xxl2o224exwiqruvtda0i',
" +
" url: 'https://plus.google.com/102817283354809142195/posts/F97fqZwJESL',
" +
" object: {
" +
" objectType: 'note',
" +
" content:
" +
" 'A picture... of a space ship... launched from earth 40 years ago.',
" +
" attachments: [
" +
" {
" +
" objectType: 'image',
" +
" url: 'http://apod.nasa.gov/apod/ap110908.html',
" +
" image: { height: 284, 506 }
" +
" }
" +
" ]
" +
" },
" +
" provider: { title: 'Google+' }
" +
"};
" +
"
" +
"console.log(JSON.stringify(mymask.maskfn(originalObj,fields)));","utf-8").mimeType("application/javascript+module").build();
context.eval(mysource);
}
- 运行效果
说明
一些额外的说明,nginx 的njs 也是支持js ,但是目前在js 的兼容上不是很好,有些特性是不支持的,还是有待提升的,graalvm 就很不错了
参考资料
https://github.com/rollup/plugins/tree/master/packages/commonjs
https://github.com/graalvm/graaljs/blob/master/docs/user/JavaScriptCompatibility.md
https://www.cnblogs.com/rongfengliang/p/13582315.html
https://github.com/nemtsov/json-mask