Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!