javascript - Unable to access function bundled by WebPack -
i have simple webapp webpack bundle javascript 1 bundle.js file used various html page.
unfortunately, if specify in webpack config file want use standalone library (librarytarget , library) can used script tag, doesn't work. seems encapsulated in module functions not available.
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> entry , output section of 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 (entry point)
function helloworld() { alert( 'hello, world!' ); } when clicking on button, receive error in console:
uncaught typeerror: ui.helloworld not function @ htmlbuttonelement.onclick (localhost/:14) for additionnal info, content of bundle.js file looks that:
var ui = ... (stuff here) function(module, exports, __webpack_require__) { __webpack_require__(79); function helloworld() { alert('hello, world!'); } /***/ }
the ui object exported bundled library same exported object of entrypoint module. if not explicitly export function module in webpack, defined within module's scope (which 1 of primary features of javascript modules). need assign module.exports object able access outside module:
/** main.js **/ function helloworld() { alert( 'hello, world!' ); } // module.exports here (in entrypoint module) same object // ui in page's scope (outside webpack) module.exports = { helloword: helloworld, }; then can access other scripts:
<script> ui.helloworld(); // 'ui.helloworld' same // 'module.exports.helloworld' above </script> if don't explicitly set module.exports in entrypoint module, default empty object { }.
Comments
Post a Comment