Reputation: 831
Let's say I have 3 functions. If I write them all one by one, below each other, all of them will be exposed to the global namespace hence global polution. So one way seems to be the following.
var test;
(function() {
test.funct1 = function(){
}
test.funct2 = function(){
}
test.funct3 = function(){
}
})
Now, we reduced the problem since the functions are not put into the global namespace. We could say, they still are, but not completely. test
will be put on the global namespace
which would have all other functions on it.
Question 1) Now, the problem still exists, if someone or some library has test
, the problem is my test
and the library's test
will be collided, which seems too bad. How do people solve this without any library/framework or whatever (without webpack) ?
Question 2) Okay, so webpack does solve the above problem. In webpack, each file is the module. That's understandable, but still, a good nice example would be great, some stuff still have to be put on global scope. I'd appreciate a good nice example.
Upvotes: 1
Views: 178
Reputation: 370929
Now, the problem still exists, if someone or some library has test , the problem is my test and the library's test will be collided, which seems too bad. How do people solve this without any library/framework or whatever (without webpack) ?
Declare the test
only inside the scope where it's necessary; don't make it global. For example, you could have:
<script>
(() => {
const test = {
funct1() {
// ...
}
// ...
};
// do stuff with test
})();
(() => {
const test = {
OTHER_METHOD() {
// ...
}
// ...
};
// do stuff with test
})();
</script>
This way, neither test
is global; they're both enclosed in their own IIFE, and all uses of a particular test
will be inside that IIFE.
some stuff still have to be put on global scope
The whole point of a module system like Webpack is to avoid having to pollute the global object; if your code is structured reasonably, there shouldn't be any need for it. But if you had to, just refer to the global object and assign to one of its properties, eg:
// someModule.js
window.SomethingGlobal = {
// stuff
};
This isn't particular to Webpack; this same exact approach for reducing global pollution is available ES6 modules
Upvotes: 1