Best Practice to import an ES6 Module in a node for Node-RED

I am looking for the best practice to import an ES6 module in a node for Node-Red. I would appreciate it if someone can provide me with some guidance here.

Here is some additional background information:

There is an library on Github which has recently been upgraded and repackaged as an ES6 module: ibmtjbot/tjbotlib/releases (Release 2.0.1)
And this repository is hosting a project with Node-Red nodes making use of an older release of the above mentioned library (Release 1.5.1):
jeancarl/node-red-contrib-tjbot

The problem I am running into is that the Node-Red nodes are CommonJS nodes. And the updated library is now an ES6 module. The best explanation I have found so far why this is troublesome: https://redfin.engineering/node-modules-at-war-why-commonjs-and-es-modules-cant-get-along-9617135eeca1

So my question is, what is the best and most efficient approach here to make things compatible again?

  1. Defining the Node-Red Nodes as "type": "module" in it's package.json and work from there? I have tried this, but this will result into all the .js files being treated as a ES modules. And from what I have seen the Node-Red loader script is a CommonJS module, so not able to import the ES modules either.
    And if I rename them to .cjs files, they are not being picked up by the Node-Red loader script (/usr/local/lib/node_modules/node-red/node_modules/@node-red/registry/lib/loader.js).

  2. Looking into how to create a "Dual Package" of the library currently packaged as an ES6 module to support both CJS as well as ESM?

Or is there maybe another option I am missing?

You are right that the whole thing is a complete pigs ear and utterly stupid.

I don't believe that it would be wise to try and define a node-red node as a type=module - I think it will break things.

You are probably faced with having to wrap an ES6 module in a way that deals with it in your own code - that way Node-RED itself doesn't need to think about it. Alternatively, you could try messing with webpack/babel to "compile" the ES6 module into your code so that it is exposed "normally".

No idea if these ideas would work I'm afraid.

In my view, ES6 modules for Node.js are fundamentally broken and should be avoided at all costs until the people designing updates to Node.js come to their senses and integrate them properly.

@TotallyInformation, thank you for confirming my suspicion about the level of support with regard to ES6 modules. So it seems that the best solution is to revert back the ES6 implementation of the library to CommonJS while maintaining the upgraded functionalities.

1 Like

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