Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export all objects in node.js

A node.js module of mine got too big, so I split it into several smaller (sub)modules.

I copy & pasted all relevant objects into each of the submodules, which now look like

var SOME_CONSTANT = 10;

function my_func() { etc... };

Now I want to export everything in each submodule, en masse, without having to explicitly say exports.SOME_CONSTANT = SOME_CONSTANT a million times (I find that both ugly and error prone).

What is the best way to achieve this?

like image 577
user124114 Avatar asked May 20 '12 15:05

user124114


People also ask

Can you export default multiple things?

Every module can have two different types of export, named export and default export. You can have multiple named exports per module but only one default export.

What is module exports in node JS?

Module exports are the instructions that tell Node. js which bits of code (functions, objects, strings, etc.) to export from a given file so that other files are allowed to access the exported code.

Can we export function in node?

Node. js treats each file in a Node project as a module that can export values and functions from the file.


1 Answers

I assume you do not want to export every local variable.

I will get around to automating this one of these days, but for now I often use this technique.

 var x1 = { shouldExport: true  } ; 

// create a macro in your favorite editor to search and replace so that

x1.name = value ; // instead of var name  = value

and

name becomes x1.name   

// main body of module

for ( var i in x1) { exports.better_longer_name[i]   = x1[i] ;} 
//or if you want to add all directly to the export scope  
for ( var i in x1) {  exports[i] = x1[i] ; }  
like image 139
george calvert Avatar answered Sep 23 '22 19:09

george calvert