Search code examples
javascriptwebpackbundlebundler

How can I use a function in a bundle.js file using <script> to include the bundle?


I have a Javascript module called out.js

export default function out(str) {   
    //Some Code 
    console.log(str); 
}

I ran the webpack bundler and created a bundle.js file. And now I am Importing it to my index.html using a tag.

<!DOCTYPE html>
<html>
  <head><script defer src="bundle.js"></script></head>
  <body>
    <script>
      out("Hello")
    </script>
  </body>
</html>

But when I get the following error on the webpage.

index.html:6 Uncaught ReferenceError: out is not defined

I have tried named exports as well as default exports for the out.js, still I get the same error.


Solution

  • 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;