【问题标题】:Unable to access function bundled by WebPack无法访问 WebPack 捆绑的功能
【发布时间】:2017-09-03 06:53:25
【问题描述】:

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

不幸的是,即使我在 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'
    },

ma​​in.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!');
    }

/***/ }

【问题讨论】:

    标签: javascript module webpack


    【解决方案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's scope (outside webpack)
    module.exports = {
      helloWord: helloWorld,
    };
    

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

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

    如果你没有在入口点模块中显式设置module.exports,它将默认为一个空对象{ }

    【讨论】:

    • 尽管这解决了问题,但在处理大型函数库(可能由其他人维护)时,您不希望手动执行此操作(在源文件中)。有什么更好的方法来全部导出?
    • @JoshuaSmith 如果是这种情况,您可以将所有函数定义为module.exports.helloWorld = function helloWorld() { ... }。据我所知,没有办法导出 all 函数,所以这可能是你能得到的最接近的函数。
    • @frxstrem - 我已按照您的步骤操作,效果很好,谢谢。但我只能使用该方法访问一个导出。假设我有两个模块,每个模块都导出一个函数,当我按照上述步骤操作时,我将如何访问这两个函数?我不完全理解您之前的评论...
    猜你喜欢
    • 2020-02-24
    • 2017-10-15
    • 1970-01-01
    • 2017-08-04
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    相关资源
    最近更新 更多