How can I use a function in a bundle.js file using ` – Cully Jun 25 '21 at 07:45

  • 1
    Also, as is mentioned in an answer, you need to get rid of the `defer` or the function won't exist when you call it. – Cully Jun 25 '21 at 07:49
  • Or you could do `window.addEventListener('load', () => window.MyFunctions.out("Hello"))` – Cully Jun 25 '21 at 07:52
  • Does this answer your question? [Browserify - How to call function bundled in a file generated through browserify in browser](https://stackoverflow.com/questions/23296094/browserify-how-to-call-function-bundled-in-a-file-generated-through-browserify) – Cully Jun 25 '21 at 07:52
  • @Cully I would want to make this bundle redistributable in a way that the global namespace is not polluted. – Tara Sharma Jun 25 '21 at 08:07
  • @Cully I also don't want this function to run as soon as the page is loaded. How can It be called like a regular function? – Tara Sharma Jun 25 '21 at 08:09
  • You can run it whenever you want. You just can't run it before the script has loaded. That's why you wait for the load event. Or you could get rid of `defer`. – Cully Jun 25 '21 at 15:49
  • I did remove the defer attribute and tried calling the function. I'm still getting the same error. – Tara Sharma Jun 25 '21 at 16:21
  • Right, because the `out` function is still not a global. – Cully Jun 25 '21 at 16:27
  • @Cully Is there any way I can run this function without putting it in the global namespace? – Tara Sharma Jun 25 '21 at 17:07
  • 1
    Not that I know of. You could make it a library (someone else could include it in their bundle). Or just namespace everything you put on window (e.g. `window.MyLibrary.out`, `window.MyLibrary.doSomething`, etc.) – Cully Jun 25 '21 at 17:11
  • 1 Answers1

    1

    You can find a good explanation and the answer here

    With my little knowledge of javascript and webpack, I spent hours looking for an answer. The short answer is you need to define your function globally to use this way. You can make out global by adding this block outside of your function.

    window.out = out;
    
    Isuru
    • 700
    • 9
    • 22