简体   繁体   English

webpack包中的导出功能

[英]Export function in webpack bundle

I am using the google Maps API which requires a callback. 我正在使用需要回调的Google Maps API。 How do I export a callback from a webpack bundle to use by an external script such as Google Maps API? 如何从webpack包导出回调以供外部脚本(如Google Maps API)使用?

HTML (Xd out key): HTML(Xd输出密钥):

<div id="hello"></div>
<script src="/js/map.bundle.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXX&callback=initMap"></script>

map.js: map.js:

var $ = require("jquery");
function initMap() {
    $("#hello").text("hello world");
}

I build the above map.js file into a webpack bundle called map.bundle.js . 我将上面的map.js文件构建到一个名为map.bundle.js的webpack包中。

Browser console error: Browser console错误:

Yc message : "initMap is not a function" name : "InvalidValueError" stack : "Error↵ at new Yc ( https://maps.googleapis.com/ma ... Yc消息:“initMap不是函数”name:“InvalidValueError”stack:“Error↵at new Yc( https://maps.googleapis.com/ma ...

I also tried adding 我也尝试过添加

module.exports = { initMap: initMap }

to map.js but that didn't help. map.js但没有帮助。

EDIT : Same question, but for using javascript functions from webpack bundles in form events: 编辑 :同样的问题,但在表单事件中使用webpack包中的javascript函数:

HTML: HTML:

<form onsubmit="sayHello(event)">
    <button type="submit">Say Hello</button>
</form>

JS: JS:

function sayHello(e) {
    e.preventDefault();
    console.log("hello");
    return false;
}

When the JS is packaged into a bundle, the "hello" is no longer printed on the console 当JS打包成捆绑包时,控制台上不再打印“hello”

Your webpack file (map.bundle.js) does not generally write any of your functions or variables into the global (in this case, window ) namespace. 您的webpack文件(map.bundle.js)通常不会将任何函数或变量写入global (在本例中为window )命名空间。

This causes problems for libraries that need to be on the global namespace like jQuery or the google maps api. 这会导致需要在全局命名空间(如jQuery或google maps api)上的库出现问题。

One way to get around this is to add initMap to the window object 解决此问题的一种方法是将initMap添加到窗口对象

var $ = require("jquery");
function initMap() {
    $("#hello").text("hello world");
}
window.initMap = initMap;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM