Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js and browser code reuse: importing constants into modules

I have some constants in JavaScript that I'd like to reuse in several files while saving typing, reducing bugs from mistyping, keeping runtime performance high, and being useful on either the node.js server scripts or on the client web browser scripts.

example:

const cAPPLE = 17;
const cPEAR = 23;
const cGRAPE  = 38;
...(some later js file)...
for...if (deliciousness[i][cAPPLE] > 45) ...

Here are some things I could do:

  1. copy/paste const list to top of each file where used. Oh, Yuck. I'd rather not. This is compatible with keeping the constant names short and simple. It violates DRY and invites all sorts of awful bugs if anything in the list changes.

  2. constant list ---> const.js

on browser, this is FINE ... script gets fed in by the html file and works fine.

but on node.js, the require mechanism changes the constant names, interfering with code reuse and requiring more typing, because of how require works....

AFAIK This doesn't work, by design, in node.js, for any const.js without using globals:

require('./const.js');
for...if...deliciousness[i][cAPPLE] > 45 ...;  

This is the node.js way:

(... const.js ....)
exports.APPLE = 17;
(... dependency.js ... )
var C = require('./const.js');
for...if...deliciousness[i][C.APPLE] > 45..... 

so I would either have to have two files of constants, one for the node.js requires and one for the browser, or I have to go with something further down the list...

3 make the constants properties of an object to be imported ... still needs two files... since the node.js way of importing doesn't match the browser. Also makes the names longer and probably takes a little more time to do the lookups which as I've hinted may occur in loops.

4 External constant list, internal adapter.... read the external constants, however stored, into internal structure in each file instead of trying to use the external list directly

const.js
exports.cAPPLE = 17

browser.js
const cAPPLE = exports.cAPPLE;
...code requiring cAPPLE...

node.js
CONST = require(./const.js)
const cAPPLE = CONST.cAPPLE;
...code requiring cAPPLE...

This requires a one-time-hit per file to write the code to extract the constants back out, and so would duplicate a bunch of code over and over in a slightly more evolved cut and paste.

It does allows the code requiring cAPPLE to continue to work based on use of short named constants

Are there any other solutions, perhaps a more experienced JavaScripter might know, that I might be overlooking?

like image 623
Paul Avatar asked Dec 27 '22 19:12

Paul


1 Answers

module.exports = Object.create({},{
        "foo": { value:"bar", writable:false, enumerable:true }
});

Properties are not writable. Works in strict mode unlike "const".

like image 85
igl Avatar answered Feb 23 '23 01:02

igl