Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda