DEV Community

Discussion on: Best Practice Tips for Writing Your JS Modules

Collapse
 
ndesmic profile image
ndesmic

It depends on what you are doing and what you want to export. Often times I'll have a main file that references several other libraries but also has the main code in it. If you adhere to doing one thing in your module this is pretty typical. If you have a collection of things you want to output and it makes sense to separate them into their own files then you'd use a index.js file (or mod.ts in Deno) to collect them for re-export. Realistically you'll be using a bundler for prod resources so this will be compiled down to a single file. If you aren't bundling, then just have multiple smaller files as they'll fetch concurrently rather than get blocked until index.js downloads.

Collapse
 
jespertheend profile image
Jesper van den Ende

I have a lot of files so I think separating them is the best way to go in that regard. I have a single index.js importing all files and exporting them again. But I'm not a big fan of this. It allows for name clashes and if a script has side effects it will execute them.
But I'm not really sure if there are any alternative methods out there. I could completely ditch index.js and require users of the library to import specific files using their complete path, but I'm not sure if this is generally an accepted way of doing this.

Thread Thread
 
ndesmic profile image
ndesmic

Node users will typically only import the the package's main script as that's just the general convention. However if the codebase it big enough you might break it into separate packages using a monorepo pattern like babel etc. Otherwise if there's code that's internal to the module but not for re-export, or if you have name clashes you'll need to manually write all the imports and exports in the index.js instead of using *. Personally I wouldn't find using multiple import paths to be a big deal but you should make sure it's documented what is in each as it might not be expected.

Thread Thread
 
jespertheend profile image
Jesper van den Ende

That sounds like a good idea. Thanks for the advice!