oracle / graaljs

A high-performance, ECMAScript compliant, and embeddable JavaScript runtime for Java
https://www.graalvm.org/javascript/
Universal Permissive License v1.0
1.78k stars 189 forks source link

Simple ES module-loading example? #273

Closed tedneward closed 3 years ago

tedneward commented 4 years ago

I read through the issue (#92) around ES modules, but I'm not sure I understand what the state-of-the-art is now in build 20. The issue I'd like to ask is for a simple ES-module example be included as part of the GraalJS/GraalVM docs, but I'm happy to contribute one if it'll help.

If I have a .mjs file that is Source-loaded, and it in turn uses an "import" to load another .mjs-suffixed file, everything should work? Is that correct?

RepComm commented 4 years ago

I've tried this and I can't get it running. A very unhelpful error is produced.

//index.mjs
import Dependency from "./dependency.mjs";

console.log("Hello from index!");

let myDep = new Dependency();
//dependency.mjs

export default class Dependency {
  constructor () {
    console.log("Hello from example dependency imported class!");
  }
}
//main.java
String srcStr = new String(Files.readAllBytes(jsPluginFile.toPath()));
Source src = Source.newBuilder("js", srcStr, pkgJsonMain).build();
this.ctx.eval(src);

Output: Error: dependency.mjs

Expected output:

Hello from index!
Hello from example dependency imported class!
RepComm commented 4 years ago

Scratch that, it's working when Source is used like this:

File file = new File("index.mjs");
Source src = Source.newBuilder("js", file).build();
this.ctx.eval(src);

Got my output!

[21:06:02] [Server thread/INFO]: Hello from index!

[21:06:02] [Server thread/INFO]: Hello from example dependency imported class!
wirthi commented 4 years ago

Hi @tedneward

We have some tests in https://github.com/graalvm/graaljs/blob/master/graal-js/src/com.oracle.truffle.js.test/src/com/oracle/truffle/js/test/interop/ESModuleTest.java

and the https://github.com/graalvm/graaljs/tree/master/graal-js/src/com.oracle.truffle.js.test/commonjs directory also gives several examples. We are currently preparing a blogpost on that topic.

CC @eleinadani

Best, Christian

eleinadani commented 4 years ago

Hi @tedneward,

If I have a .mjs file that is Source-loaded, and it in turn uses an "import" to load another .mjs-suffixed file, everything should work? Is that correct?

Yes, correct. Files with extension .mjs are loaded as ES modules.

In addition to the links above, we also have some documentation in https://github.com/graalvm/graaljs/blob/master/docs/user/NodeJSVSJavaScriptContext.md#ecmascript-modules-ecm but as @wirthi wrote, we will expand the documentation soon.

a-langer commented 4 years ago

Hi @tedneward , I can recommend a third-party library https://github.com/a-langer/jsr223-commonjs-modules that implements CommonJS modules.