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.
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.