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