Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

javascript - how does webpack solve global polution?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...