繁体   English   中英

无法访问WebPack捆绑的功能

[英]Unable to access function bundled by WebPack

我有一个非常简单的webapp,其中WebPack将javascript捆绑到一个由各种html页面使用的bundle.js文件中。

不幸的是,即使我在webpack配置文件中指定我想将它用作脚本标记可以使用的独立库( libraryTargetlibrary ),它也不起作用。 似乎所有东西都封装在模块中,所以我的功能不可用。

的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>

我的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(切入点)

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

单击我的按钮时,我在控制台中收到此错误:

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

对于其他信息,我的bundle.js文件的内容看起来像这样:

var ui = ...

(stuff here)

function(module, exports, __webpack_require__) {

    __webpack_require__(79);

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

/***/ }

捆绑库导出的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's scope (outside webpack)
module.exports = {
  helloWord: helloWorld,
};

然后,您可以从其他脚本访问它:

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

如果未在entrypoint模块中显式设置module.exports ,则默认为空对象{ }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM