Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to access function bundled by WebPack

I have a very simple webapp where WebPack bundle the javascript into one bundle.js file that is used by various html page.

Unfortunately, even if I specify in the webpack config file that I want to use it as a standalone library (libraryTarget and library) that can be used by script tag, it doesn't work. Everything seems to be encapsulated in module so my functions are not available.

index.html

<!DOCTYPE html>
<html lang="EN">
<head>
    <title>Play! Webpack</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
    <body>
    <app>
        Loading...
    </app>
    <script type="text/javascript" src="/bundles/bundle.js" charset="utf-8"></script>
    <button type="button" onclick="ui.helloWorld()">Click Me!</button>
    </body>
</html>

entry and output section of my webpack.base.config.js

entry: [
        './app/main.js'
    ],
    output: {
        path: buildPath,
        filename: 'bundle.js',
        sourceMapFilename: "bundle.map",
        publicPath: '/bundles/',
        libraryTarget: 'var',
        library: 'ui'
    },

main.js (entry point)

function helloWorld() {
    alert( 'Hello, world!' );
}

When clicking on my button, I receive this error in the console:

Uncaught TypeError: ui.helloWorld is not a function
    at HTMLButtonElement.onclick (localhost/:14)

For additionnal info, the content of my bundle.js file looks something like that:

var ui = ...

(stuff here)

function(module, exports, __webpack_require__) {

    __webpack_require__(79);

    function helloWorld() {
        alert('Hello, world!');
    }

/***/ }
like image 582
Jean-François Côté Avatar asked Apr 07 '17 19:04

Jean-François Côté


1 Answers

The ui object exported by the bundled library is the same as the exported object of the entrypoint module. If you do not explicitly export a function from a module in webpack, it will only be defined within that module's scope (which is one of the primary features of JavaScript modules). You need to assign it to the module.exports object to be able to access it from outside the module:

/** main.js **/

function helloWorld() {
    alert( 'Hello, world!' );
}

// module.exports here (in the entrypoint module) is the same object
// as ui in the page's scope (outside webpack)
module.exports = {
  helloWord: helloWorld,
};

Then you can access it from your other scripts:

<script>
  ui.helloWorld(); // 'ui.helloWorld' is the same as
                   // 'module.exports.helloWorld' above
</script>

If you don't explicitly set module.exports in the entrypoint module, it will default to an empty object { }.

like image 92
Frxstrem Avatar answered Oct 16 '22 10:10

Frxstrem