Default and named exports in node.js

faikdjikic

Faik Djikic

Posted on March 28, 2024

Default and named exports in node.js

As an "old fart" programmer I tend to write a lot of reusable code and improve it with each usage. Eventually, now and then, I encounter compatibility issues, and although it is on a small scale (usually, the code is used only by my team and me) it still gets to be a PitA. One of those was expanding a commonly used node module that exports a single function as default:

module.exports=function(){
console.log("hello");
}
Enter fullscreen mode Exit fullscreen mode

to multi-function module with named exports like this:

const fn1=function(){
console.log("hello");
}
const fn2=function(){
console.log("hi");
}
const fn3=function(){
console.log("howdy");
}
module.exports={fn1,fn2,fn3}
Enter fullscreen mode Exit fullscreen mode

Simple and clean expansion, but one that would break compatibility with every other module that used this expecting a default export:

const greeting=require('./hello');
Enter fullscreen mode Exit fullscreen mode

I solved it using a rather unorthodox approach and it seems to be working (tested down to version 16.20.2 and up to 21.5.0)

Here's the module code:

const fn1 = function () {
    console.log("hello");
}
const fn2 = function () {
    console.log("hi");
}
const fn3 = function () {
    console.log("howdy");
}
fn1.fn1 = fn1;
fn1.fn2 = fn2;
fn1.fn3 = fn3;
module.exports = fn1;
Enter fullscreen mode Exit fullscreen mode

and here's the implementation:

const greeting = require('./hello');
const { fn1, fn2, fn3 } = require('./hello');
greeting();
fn3();
fn1();
fn2();
Enter fullscreen mode Exit fullscreen mode

It works perfectly and I'm not aware of any downsides. I would appreciate any suggestion on how this could be wrong or potentially dangerous before I implement it in production.

On the other hand, if it is safe to use, it might be a useful approach in similar situations

💖 💪 🙅 🚩
faikdjikic
Faik Djikic

Posted on March 28, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related