2017-04-07 106 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