How to enable Ecmascript Modules in js shell?

The following exits

#!/usr/bin/env -S JS_STDERR=err.txt /home/user/.jsvu/engines/spidermonkey/spidermonkey --enable-import-attributes --enable-top-level-await
import * as data from "./exports.json" with {type: "json"};
console.log(data);
import * as data from "./exports.js";

How to enable Ecmascript Modules in js shell?

This works for me:

$ cat test.json
{"x":1,"y":2}

$ cat test.js
import * as data from "./test.json" with {type: "json"};
console.log(data.default.x, data.default.y);

$ js --enable-import-attributes -m test.js
1 2

edit: fixed the flag order after seeing later posts

How to do that using the shebang line where we are not running the script from a TTY or commandline, where js is launched by another application?

#!/usr/bin/env -S JS_STDERR=err.txt /home/user/.jsvu/bin/spidermonkey --enable-import-attributes --enable-uint8array-base64 --enable-arraybuffer-resizable --enable-top-level-await --enable-async-iterator-helpers --enable-iterator-helpers

import * as data from "./test.json" with {type: "json"};
console.log(data.default.x, data.default.y);

When I put -m in a shebang line without a “test.js” value, that is, I’m referring to the current script beneath the shebang line the script exists.

In err.txt we see js is expecting a file name when -m is in shebang line, which means we would have to create another file to point to aqnd just use a shell script with -m test.js, instead of an -m without pointing to a separate file meaning refer to the current script.

Error: can't open --enable-import-attributes: No such file or directory

In V8’s d8 Ecmascipt Modules are supported out of the box. In QuickJS -m works on the shebang line out of the box, too

#!/usr/bin/env -S /home/user/bin/qjs -m --std
// QuickJS Native Messaging host
// guest271314, 5-6-2022
import {webserver} from './webserver.so';

The -m option takes a filename argument. The #! invocation will append the script name to the end. So it should work with your env -S if you put -m at the end of the command line.

It works for me with jandem’s example. My shebang line is: #!/bin/env -S /home/sfink/src/mozilla4/obj-debug-js/dist/bin/js --enable-import-attributes -m

1 Like

Sorry my bad, I changed the order of the flags without testing that version. I fixed the example.

1 Like