简体   繁体   中英

Node.js sharing code between backend and frontend

I want to share some code between node.js back-end and front-end, like converting a certain date format (not natively supported by Date) into Date object.

First off, if sharing code between backend and frontend is terrible practice, let me know.

If not: the problem I am running into is that for node.js, I would use a module, and use module.exports to export the util functions. I want to avoid using front-end modules for more browser support. So how could I use the same js file in backend and frontend?

A simple way to use .js files both in node and on the front-end is to check for module and module.export objects before assigning to them.

Example convert-date.js file:

function convertDate( date) {
   // blah blah
}

if(this && typeof module == "object" && module.exports && this === module.exports) {
   module.exports = convertDate;  // for example
}

which results in declaring convertDate as a global function name on the front-end while allowng it to be required in node using

const convertDate = require( pathOfConvertDate.js);

To limit the number of globals created put more complex code inside an IIFE which returns the value to be exported:

const convertDate = (()=>{ ..... return convertDate;})();
if( this etc...) module.exports = convertDate;

A variation of the above is to mandate the presence of a common utilities object on the front-end which must be declared before file inclusion. Using Util as an example name, the export code becomes more like

if(this && typeof module == "object" && module.exports && this === module.exports) {
   module.exports = convertDate;  // for example
}
else if(typeof Util == "object" && Util) {
   Util.convertDate = convertDate;
}
else {
    throw( Error("Front-end 'Util' export object not found'));
}

FWIW I don't know how common this kind of usage is. I do know it works with file:// protocol and simplifies writing test code that runs equally well on the back or front-end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM