graalvm 支持mjs 模块的加载,以下是一个简单的学习demo
环境准备
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dalong.ex</groupId>
<artifactId>qlex-learnint</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<encoding>UTF-8</encoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>QLExpress</artifactId>
<version>3.2.0</version>
</dependency>
<!-- 如果使用了js-scriptengine 以下可选-->
<!-- <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>
</dependencies>
<build>
<!-- Maven Shade Plugin -->
<finalName>my-expression-app</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>Application</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
- application.java
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.IExpressContext;
import org.graalvm.polyglot.*;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.IOException;
/**
@author dalong
*/
public class Application {
public static void main(String[] args) throws ScriptException, NoSuchMethodException, IOException {
// qlExpression();
method1();
method2();
method3();
//method4();
}
public static void method1() {
System.out.println("Hello Java!");
try (Context context = Context.newBuilder().allowAllAccess(true).build()) {
context.eval("js", "print('Hello JavaScript!');");
context.eval("js", "let user = {name:\"dalong\",age:333}; print(JSON.stringify(user))");
java.math.BigDecimal v = context.eval("js",
"var BigDecimal = Java.type('java.math.BigDecimal');" +
"BigDecimal.valueOf(10).pow(20)")
.asHostObject();
System.out.println(v.toString());
}
}
public static void method2() throws ScriptException, NoSuchMethodException {
ScriptEngine eng = new ScriptEngineManager().getEngineByName("js");
eng.eval("let user = {name:\"dalong\",age:333}; print(JSON.stringify(user))");
}
// 此为测试代码
public static void method3() throws IOException {
Value value =null;
Source mysource =Source.newBuilder("js","import demo from \"src/main/resources/demo2.js\"\n" +
"let info = demo()\n" +
"console.log(\"-----js-------\")\n" +
"console.log(info)\n" +
"console.log(\"-----js-------\")\n","demoeeee").mimeType("application/javascript+module").build();
try (Context context = Context.newBuilder().allowAllAccess(true).build()) {
value = context.parse(mysource);
value.execute();
} catch (PolyglotException e) {
if (e.isSyntaxError()) {
SourceSection location = e.getSourceLocation();
} else {
}
throw e;
}
finally {
}
}
// 通过网络模式的不支持
public static void method4() throws IOException {
Value value =null;
// this not work current only support localfs
Source mysource =Source.newBuilder("js","import demo from \"https://raw.githubusercontent.com/rongfengliang/graalvm-js-learning/master/demo.js\"\n" +
"let info = demo()\n" +
"console.log(\"-----js-------\")\n" +
"console.log(info)\n" +
"console.log(\"-----js-------\")","demoeeee").mimeType("application/javascript+module").build();
try (Context context = Context.newBuilder().allowAllAccess(true).build()) {
value = context.parse(mysource);
value.execute();
} catch (PolyglotException e) {
if (e.isSyntaxError()) {
SourceSection location = e.getSourceLocation();
} else {
}
throw e;
}
finally {
}
}
}
- demo2.js
就是一个mjs 的代码,同时集成了java 的调用
function demo() {
var BigDec = Java.type('java.math.BigDecimal');
var bd = new BigDec("0.1");
console.log(bd.add(bd).toString());
return "dalong rong feng"
}
export default demo
- 核心说明
对于加载mjs 我们需要通过source 对象构建,同时需要指定mimetypeapplication/javascript+module
对于需要集成java 调用的需要在context 添加allowAllAccess
运行效果
说明
基于本地的模式运行mjs ,可以增强系统的灵活性,但是基于本地模式的灵活性还是不够好(当然直接访问网络会有安全的问题)
实际我们可以基于模块化的模式运行(比如browserify,可以灵活的加载依赖)
参考资料
https://www.graalvm.org/reference-manual/js/JavaScriptCompatibility/
https://github.com/graalvm/graaljs/blob/master/docs/user/JavaScriptCompatibility.md