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

178
Visualizações
How to make an npm package available to multiple JS modules?

Context:

I am transitioning from the traditional js/html way of doing frontend development:

<script src="link-to-the-js-file"></script>

<!-- Now, just use the library... -->

To the modern npm/js-modules/webpack way:

npm install whatever

require('whatever')

whatever.doSomething();

Question:

I am confused about when and how to require packages that will be used in multiple modules.

Let's say I have two features in my site for which I want to use axios.

I would do:

file: feature.js

/**
 * Some JS module where I'll use axios
 */

const axios = require('axios');

export default () => ({
...

   axios.doWhatever();

...
});

But what if there is another module that also needs axios?

If I require it in another-file.js, won't I have axios included multiple times in my compiled JS?

So this leads me to think... okay, I will attach it to the window scope and just use it from there whenever I want.

And go with something like:

file: global-file.js

window.axios = require('axios');

But I don't know if this is good practice.

I know opinion based questions are not allowed here, but there must be a solid generic approach for this. I don't want to "just make it work", I want to do things in a correct manner. I'll appreciate your help.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

From the Node documentation:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

So you are basically (in most cases) using the same object/file. But if you don't want to repeat yourself in multiple files you can just add it to the global scope like so:

axios = require('axios ');

See more on Node.js caching.

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