I am using webpack and firebase.
I have this line in my package.json > "start": "webpack-dev-server ./index.js",
In my index.js file I have function
logUserIn(){ //does stuff };
In my index.html file I have this line > <input type="submit" onclick=logUserIn() value="Log in">
When I click that button I get this error > Uncaught ReferenceError: logUserIn is not defined
I also have this line in my index.html file > <script src="bundle.js"></script>
that should link to the bundle file that contains index.js correct?
Finally, I have done a console.log in the index.js saying console.log('hello')
, when I refresh the page, the hello appears thus meaning that the index.html is calling index.js through bundle.js so why on earth will it not recognize my method name?
It is definitely not a typo either as i have copied and pasted
Advertisement
Answer
When you use Webpack, you are assumed to be using modules. If your code isn’t organized this way, it can create some issues.
Specifically to your problem, your function logUserIn()
is there, but it’s inside a module, meaning that it’s a private function. It’s not seen in the global scope, so your index.html
can’t “see” the function to call it.
In order to make it globally available, you’ll need to export the function.
However, unless you have a specific reason to have the logUserIn()
in the HTML, I would recommend switching up your code. Typically you want to keep your markup and your logic separate, so in this case your code would look more like:
Javascript
document.getElementById('loginButton').onclick = logUserIn
HTML
<input type="submit" id="loginButton" value="Log in">
Also, if the button in question is a form, you’ll need to overwrite the default functionality of a form with e.preventDefault()
.