I have a js file containing a series of functions. I want to call those functions both in my ui node backend js file, and also in my ui node frontend vue file.
The js file is included in the frontend umd file luckily, so I have it available in the backend and the frontend. However my node's NodeJs backend js file only seems to allow a commonjs module to be loaded via require, while my node's frontend vue file only seems to allow an es6 module to be loaded via import.
I experimented a lot to find a solution. And ChatGpt gave me a lot of of realistic looking examples, but they all failed unfortunately...
Does anybody whether this is possible?
And if yes: how
Hi Julian,
Thanks for joining!
Hmm I thought that I had to make my js file (containing a series of functions) to support both CommonJs (for my node backend) and ESM (for my vue frontend).
But you make me thinking I am talking nonsense. I see here that Vite build (which we execute via npm run build in the D2 dashboard) should convert automatically CommonJs modules to ESM modules.
Will do some more tests this weekend into that direction, and report my feedback here.
I was pleasantly surprised recently to stumble upon a Node.js developer who has FINALLY grasped the nettle that is being able to require ESM modules in CommonJS ones. Something that is really starting to hurt Node.js now. Still early days so it will be a few years yet before it becomes mainstream probably but long overdue.
Ok I finally found a way to use a js file both in the backend and frontend of a ui node. Not sure whether it is the best way to achieve it, but at least it seems to work. Will describe how to do it, in case anybody else ever needs it.
For the ui-svg node in D2, I created following directory structure:
As you can see in the debugger, all functions are available:
By default Vite will - during the build - only add npm packages (from the node_modules folder) into the bundle (.umd file), which you use in the vue file. So we need to specify in vite.config.js that our js file also needs to be transpiled from commonJs to an ESM module, and that this ESM module code needs to be included into the bundle file: