DEV Community

Discussion on: What the heck are CJS, AMD, UMD, and ESM in Javascript?

Collapse
 
karataev profile image
Eugene Karataev

Can you please clarify?

When CJS imports, it will give you a copy of the imported object.

Let's say we have three files:

// obj.js
module.exports = {
  a: 42
};

// bar.js
const fooObj = require('./obj');

console.log('obj from bar', fooObj);

// index.js
const obj = require('./obj');

obj.a = 50;
console.log('obj', obj);

require('./bar');
Enter fullscreen mode Exit fullscreen mode

Console output after run node index.js:

obj { a: 50 }
obj from bar { a: 50 }
Enter fullscreen mode Exit fullscreen mode

It's clear that index.js and bar.js share the same object from obj.js.

Collapse
 
almaember1098 profile image
almaember

Not like you should be changing modules anyways...

Collapse
 
mudlabs profile image
Sam

Because obj.js is exporting an object literal. The first time you require obj.js the object is instantiated, and assigned memory allocation. Every time you require it, it's the same object, from memory. If obj.js was exporting a function that returned an abject, well that would be different.

Collapse
 
karataev profile image
Eugene Karataev

If obj.js was exporting a function that returned an abject, well that would be different.

Agree. But in this case the exported function will be the same for all modules (i.e. the function will not be copied for every import).

Thread Thread
 
mudlabs profile image
Sam

Right