我有一个非常简单的webapp,其中WebPack将javascript捆绑到一个由各种html页面使用的bundle.js文件中。
不幸的是,即使我在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!');
}
/***/ }
答案 0 :(得分:17)
捆绑库导出的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
,则默认为空对象{ }
。