My own JavaScript library - errors for either not finding or already defined functions

  • Platform information: docker image: “openhab/openhab:3.4.1-alpine”

Hi!

I am writing rules in ECMA Script in the browser UI.
To avoid code duplication in my rules, I try to collect common code in external JS files. I followed JavaScript Scripting - Automation | openHAB to create an initial npm package and installed it.

I now have my code in
openhab_conf/automation/js/node_modules/local_oh_lib/index.js
with following exports:

module.exports = {
  by_item_name, // function by_item_name(a, b) {
  remove_emojis, // function remove_emojis(text) {
  this_func_name // function this_func_name() {
};

openhab_conf/automation/js/node_modules/local_oh_lib/package.json contains

{
  "name": "local_oh_lib",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

In my rules I require my lib via

const { by_item_name, remove_emojis, this_func_name } = require('local_oh_lib')

The thing now is, that I get errors with subsequent calls to these functions.
So either I get something like

2023-03-12 10:47:45.890 [ERROR] [internal.handler.ScriptActionHandler] - Script execution of rule with UID 'oh-bot-cmd-bdeb4c66b6' failed: org.graalvm.polygl ot.PolyglotException: SyntaxError: Variable "by_item_name" has already been declared

or

2023-03-12 10:47:55.944 [ERROR] [internal.handler.ScriptActionHandler] - Script execution of rule with UID 'oh-bot-cmd-bdeb4c66b6' failed: org.graalvm.polygl ot.PolyglotException: ReferenceError: "this_func_name" is not defined

when I remove a function again from the require statement (due to already declared), depending on what gets used.

I clearly miss something essential here but cannot figure it out.

Any help highly appreciated,
thanks,
Alex.

Subsequent runs of a rule use the same context, so you can’t use const because you can’t re-declare a const value. Just use var instead to import your functions.

2 Likes

Argh. Yes, this was it … Thanks a lot!