3
我有一个非常简单的Web应用程序,其中WebPack将JavaScript捆绑到一个由各种html页面使用的bundle.js文件中。无法访问WebPack捆绑的功能
不幸的是,即使我在webpack配置文件中指定我想将它用作脚本标记可以使用的独立库(libraryTarget
和library
),它也不起作用。一切似乎都封装在模块中,所以我的功能不可用。
的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!');
}
/***/ }
尽管这解决了问题,但在处理大型函数库(可能由其他人维护)时,您不希望手动执行此操作(在源文件中)。任何更好的出口方式? –
@JoshuaSmith如果是这样的话,你可以将所有的函数定义为'module.exports.helloWorld = function helloWorld(){...}'。据我所知,没有办法导出*所有*函数,所以这可能是最接近你会得到的。 – Frxstrem