"import" in JS macros?

@careyh Dear sir, it has been years since visiting here lost time. Thank you all for producing the great tool that was my indispensable friend for so many years!

I have accumulated a lot of macros in last years and making Komodo Edit something like a special Word for manipulating all kinds of text files.

I have a question for you: is it possible to write something like below in JS macros? Thank you!

import myConverter from "./lib/lib1.js"

Great question @surfactant.

You actually can do this. There’s a “hacky” way then a “nicer” way.

Komodo uses the CommonJS system of importing code so if you look through the code base you’ll see a lot of require("module/filename"), eg. OpenKomodoIDE/commando.js at master · ActiveState/OpenKomodoIDE (github.com)

We populated a ton of modules into Komodo and we do that using the require.setRequirePath() function, eg. OpenKomodoIDE/bootstrap.js at master · ActiveState/OpenKomodoIDE (github.com)

The Hacky Way

Inside your userscript/macro you could call require.setRequirePath() directly, adding your library code directly. NOTE: editing the library code and re-running your userscript will NOT reload the code. You have to restart Komod and re-run the script

Brief Example

With the following code in a file called stuff.js

(function() {
   this.stuff = function()
   {
      console.log("doing stuff", 1+1);
   }
}).apply(module.exports); // Note that this line is required by require

You can add the “module” to require using the file url (note: NOT file path).

// Make `require` aware of your code
// First arg will be the name of the module
// This is obviously a Windows path.  Unix path should be intuitive enough though
// The *stuff.js* file is in this folder
window.require.setRequirePath("stuff/", "file:///C:/path/to/folder/")
// name after the `/` is the name of the file that exports the module code without the file extension
let stuff = require("stuff/stuff")
stuff.stuff()

So that’s the basic hack that I just tried in a Userscript and it works well BUT

The Nicer Way

I would organize all my JavaScript helper code into a Komodo module/addon that uses the bootstrap.js method of installing the addon code.
Here’s an example module: OpenKomodoIDE/src/modules/scope_bookmarks at master · ActiveState/OpenKomodoIDE (github.com). So all of your helper JS files would go into the content folder.

Here’s more documentation about creating an addon: Komodo 12 Documentation (activestate.com). But you should be able to get most of the way there by coping the scope_bookmarks addon and altering it to your needs.

That should get you to where you want to be.

  • Carey
1 Like

@careyh Great thanks for sharing the solutions! Let me try them carefully!