I am looking for a possibility to write library files that could be reused in different rules script files.
I in Jython this was possible by placing them in a separate lib folder.
Is there a solution in JS?
I have tried to define a folder under automation/js/lib and also folder automation js_lib. Both time the result was the same:
referenced in my rules js file:
const lib = require('../../js_lib');
2022-01-10 13:53:30.020 [ERROR] [ipt.internal.ScriptEngineManagerImpl] - Error during evaluation of script 'file:/openhab/conf/automation/js/test.js': org.graalvm.polyglot.PolyglotException: TypeError: Cannot load CommonJS module: '../../js_lib'
I believe that JS Scripting follows Node.js standards for modules. The root folder where it will look for modules is $OH_CONF/automation/js/node_modules.
You can create folders and files there to import your libraries. However, to use requires like that I think there are some conventions you need to follow. I’ve only tried it using a full Node module so I’ve a package.json and index.js file. But I think even without those, you still need to add your functions/classes to exports in order for them to be visible to the code that is calling require.
It would probably be worth while going through one of the many “how to create an npm module” tutorials out there. That will teach you the proper way to do it.
There are other ways that can work too including using load to “inline” the .js file into your rule
Node.js also support relative imports from the root folder. node_modules is an additional search location for modules. In my older fork of jsscripting it worked exactly this way. It is on my todo list to check why the same is not possible with the current version. If I find a solution I’ll create a PR on github.