I've replied directly to him but maybe it's interesting for others too.
This is the TL;DR version of how I bootstrap CommonJS equivalent of `__dirname` and `__filename` at the entry point level.
#!/usr/bin/env gjs
const { File } = Gio;
const PROGRAM_EXE = File.new_for_path(GLib.get_current_dir())
.resolve_relative_path(imports.system.programInvocationName);
const [
__dirname,
__filename
] = [
getProgramDir(PROGRAM_EXE).get_path(),
PROGRAM_EXE.get_path()
];
print(__dirname);
print(__filename);
function getProgramDir(programFile) {
const info = programFile.query_info('standard::', Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS, null);
if (info.get_is_symlink()) {
const symlinkFile = programFile.get_parent().resolve_relative_path(info.get_symlink_target());
return symlinkFile.get_parent();
} else {
return programFile.get_parent();
}
}
Which gives me an easy way to pollute the import search path as such:
imports.searchPath.push(__dirname);
Now, if inside this very same file, as entry point, you have a folder, let's call it `test`, and a `module.js` file inside such folder with the following content:
function waitWhat() {
print('here I am');
}
this is how you'd use it from the entry point:
const module = imports.test.module;
module.waitWhat();
In few words, when you push `imports` you add paths to synchronously look for, and anything that leaks in the module scope is exported.
Accordingly, a reasonable patter to export without leaking everything per each module is to use an IIFE like:
// var because gjs module system is a bit messed up
// so if you use const in the module scope it will
// be exported but it will also trigger warnings
// once accessed, and same goes for let.
var {
method,
util
} = (() => {'use strict';
const method = () => {};
let util = () => {};
// your export
return { method, util };
function test() {}
})();
// if needed
this.default = method;
As you can see you could even follow the Babel / Webpack pattern of exporting `default` (but you need to explicitly import that too).
Good luck with the rest of your project 👋