0

Here is my problem. I have two js files:

hello.js:

function hello() {
    return "Hello World";
}
console.log(hello());

bye.js

function bye() {
    return "bye-bye";
}
console.log(bye());

I built a bundle using webpack.

Now I put the bundle file in the html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script src="./src/bundle.js" type="text/javascript"></script>
    <!-- HERE --!>
</body>
    </html>

and everything is great :-)

However, the problem arises when I want to add the following code after <script src="./src/bundle.js"... >

I added:

<script>
   hello();
</script>

and I got the error:

Uncaught ReferenceError: hello is not defined

What I understand is that Webpack encapsulates the functions that build the bundle file. I want to know how to use webpack so functions 'hello' and 'bye' will be able to be exported from the bundle file and be re-used outside the bundle file.

CrazySynthax
  • 13,662
  • 34
  • 99
  • 183

1 Answers1

0

Put your function on the window object:

function hello() {
    return "Hello World";
}
console.log(hello());
window.hello = hello;

But keep in mind that this approach is unusual. You should avoid setting values on the window object and writing JavaScript text in your HTML files if you work with Webpack.

ideaboxer
  • 3,863
  • 8
  • 43
  • 62