Using modules in gjs

Hi there

I am reading through the gjs guide on imports and modules and I came across the statement below.

Modules are searched in paths defined in the array imports.searchPath. You can modify the value of imports.searchPath to include the directories where to look for modules.

However, when I look at the source code for Gnome sound recorder, nobody seems to be adding a module path to imports.searchPath as suggested here.

When you look at utils.js file, the comment on the first line indicates something is being exported and it is being used in row.js. Nothing is being added to imports.searchPath. My assumption is, builder is adding the modules behind the scenes.

But when I try to do the same, I get the error below,

JS ERROR: ImportError: No JS module ‘dialog’ found in search path

What is going on here that nobody seems to be talking about? How do I ensure my modules are added to the search path just like in Gnome sound recorder.

gnome-sound-recorder uses the imports.package module which (among other things) sets up the search path.

So how does gnome-sound-recorder exactly use the imports.package module? Is there some sort of configuration file similar to Node’s package.json file for specifying packages an app depends on? It doesn’t just work out of the box, does it?

For GI libraries it requires, gnome-sound-recorder uses imports.package.require:

    'Gdk': '4.0',
    'GdkPixbuf': '2.0',
    'GLib': '2.0',
    'GObject': '2.0',
    'Gtk': '4.0',
    'Gst': '1.0',
    'GstAudio': '1.0',
    'GstPlayer': '1.0',
    'GstPbutils': '1.0',
    'Adw': '1',

The executable wrapper calls package.init() like so:

    name: "@APPLICATION_ID@",
    version: "@PACKAGE_VERSION@",
    prefix: "@prefix@",
    libdir: "@libdir@"

These fields are filled by the at “compile” time.

This tells the package module where to find GResource bundle, which in turn keeps the application’s JavaScript files in a path structure of <application-path>/js/fileName.js. These files will be available as imports.fileName and so on.

Thanks. This answers my question. I can now modularize my code with ease.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.