Unable to access bundled features using WebPack

I have a very simple webapp where WebPack combines javascript into one bundle.js file, which is used on different html pages.

Unfortunately, even though I will point out in webpack configuration file that I want to use as a stand-alone library ( libraryTargetand library) that can be used script tag, it does not work. Everything seems to be encapsulated in the 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>

input 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 I click on my button, I get this error in the console:

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

For additional information, the contents of my bundle.js file look something like this:

var ui = ...

(stuff here)

function(module, exports, __webpack_require__) {

    __webpack_require__(79);

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

/***/ }
+4
1

ui, , . webpack, ( JavaScript). module.exports :

/** main.js **/

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

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

:

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

module.exports , { }.

+5

Source: https://habr.com/ru/post/1674334/


All Articles