Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

138
Vistas
Shared state in ES6 vs CommonJS modules

I can share state via CommonJS modules, but not via ES6 modules.

I'm wondering why, and want to know how to share state via ES6 modules.

CommonJS

main.js:

const shared = require('./shared.js');
shared.val = 2;
require('./child.js');
console.log('main.js', shared);

child.js:

const shared = require('./shared.js');
console.log('child.js', shared);

shared.js:

module.exports = {val:1};

Result:

$ node main.js
child.js { val: 2 }
main.js { val: 2 }

ES6

main.mjs:

import shared from './shared.mjs';
shared.val = 2;
import a from './child.mjs';
console.log('main.mjs', shared);

child.mjs:

import shared from './shared.mjs';
console.log('child.mjs', shared);
export default undefined;

shared.mjs:

export default {val:1};

Result:

$ node main.mjs
child.mjs { val: 1 }
main.mjs { val: 2 }
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can share state in exactly the same way.

What you can't though is run code in between imports. They all should be at the top of your file because they are basically hoisted to the top.

If you change child to something like this:

import shared from './shared.mjs';

export default () => {
  console.log('child', shared);
};

And then run that after you've changed shared:

import shared from './shared.mjs';
import runChild from './child.mjs';

shared.val = 2;

console.log('main', shared);
runChild();

They'll both have { val: 2 }.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda