2017-04-07 109 views
3

我有一个非常简单的Web应用程序,其中WebPack将JavaScript捆绑到一个由各种html页面使用的bundle.js文件中。无法访问WebPack捆绑的功能

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

/***/ } 

回答

4

ui对象由捆绑库导出的数据与入口点模块的导出对象相同。如果您没有明确地从webpack中的模块中导出函数,那么它只会在该模块的范围内定义(这是JavaScript模块的主要功能之一)。你需要将其分配到module.exports对象能够从访问它的模块外:如果你没有明确

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

/** 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, 
}; 

然后你可以从其他脚本访问在入口点模块中设置module.exports,它将默认为一个空对象{ }

+0

尽管这解决了问题,但在处理大型函数库(可能由其他人维护)时,您不希望手动执行此操作(在源文件中)。任何更好的出口方式? –

+0

@JoshuaSmith如果是这样的话,你可以将所有的函数定义为'module.exports.helloWorld = function helloWorld(){...}'。据我所知,没有办法导出*所有*函数,所以这可能是最接近你会得到的。 – Frxstrem