Basic webpack not working for button click function - Uncaught Reference error: undefined

JavascriptWebpack

Javascript Problem Overview


I have a basic HTML page with a button:

<!DOCTYPE html>
<html lang="en">
<head>
  ...
</head>
<body>
    <button id="button" onclick="uclicked()">Click me</button>
    <script src="./bundle.js"></script>
</body>
</html>

and an app.js:

//(function(){
    console.log('started up')
    function uclicked(){
        console.log('You clicked');
    }
//})();

webpack is installed and webpack --watch succeeds. The webpack.config.js is:

module.exports={
    entry: './app.js',
    output: {
        path: __dirname,
        filename: 'bundle.js'
    }
}

When I load the page console.log is working but when I push the button I get Uncaught ReferenceError: uclicked is not defined.

If I replace <script src="./bundle.js"></script> with <script src="./app.js"></script> and bypass webpack the button clicks fine. Why doesn't this basic webpack setup work?

Javascript Solutions


Solution 1 - Javascript

When you run the file over webpack, webpack will try not to litter the global scope and so the function will not be made available globally by default.

If you want the function to be accessible outside the scope of he JS file, you should put it in the global scope.

function uclicked() {
  // do something
}
window.uclicked = uclicked;

Or just:

window.uclicked = function() {
  // do something
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmcktimoView Question on Stackoverflow
Solution 1 - JavascriptShiva NandanView Answer on Stackoverflow