导出webpack包中的函数 [英] Export function in webpack bundle
问题描述
我正在使用需要回拨的Google地图API。
HTML(Xd输出密钥):
$ b如何从webpack包中导出回调以供外部脚本(如Google Maps API)使用?$ b
< 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:
var $ = require(jquery);
函数initMap(){
$(#hello)。text(hello world);
}
我建立了上面的 map.js
文件转换为名为 map.bundle.js
的webpack包。
浏览器控制台错误:
$ b
Yc消息:initMap不是函数名称:InvalidValueError
stack:在新Yc处的错误键( https://maps.googleapis.com/ma ...
blockquote>
我也尝试添加
module.exports = {initMap:initMap}
到
map.js
但是didn'
编辑:同样的问题,但是在表单事件中使用webpack包中的javascript函数:
HTML:
< form onsubmit =sayHello(event)>
< button type =submit> Say Hello< / button>
< / form>
JS:
函数sayHello(e){
e.preventDefault();
console.log(hello);
返回false;
}
当JS打包成捆时,hello不再打印在控制台上
解决方案您的webpack文件(map.bundle.js)通常不会将任何函数或变量写入
全局
(在这种情况下,window
)命名空间。
这会导致需要位于全局名称空间(如jQuery或Google Maps API)中的库出现问题。
解决此问题的一种方法是添加<$ c
$ bvar $ = require(jquery); $ c> initMap
函数initMap(){
$(#hello)。text(hello world);
}
window.initMap = initMap;
I am using the google Maps API which requires a callback. How do I export a callback from a webpack bundle to use by an external script such as Google Maps API?
HTML (X-d out key):
<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:
var $ = require("jquery"); function initMap() { $("#hello").text("hello world"); }
I build the above
map.js
file into a webpack bundle calledmap.bundle.js
.Browser console error:
Yc message : "initMap is not a function" 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.EDIT: Same question, but for using javascript functions from webpack bundles in form events:
HTML:
<form onsubmit="sayHello(event)"> <button type="submit">Say Hello</button> </form>
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
解决方案Your webpack file (map.bundle.js) does not generally write any of your functions or variables into the
global
(in this case,window
) namespace.This causes problems for libraries that need to be on the global namespace like jQuery or the google maps api.
One way to get around this is to add
initMap
to the window objectvar $ = require("jquery"); function initMap() { $("#hello").text("hello world"); } window.initMap = initMap;
这篇关于导出webpack包中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!