繁体   English   中英

使用Webpack时,Google Maps无法访问回调函数

[英]Google Maps cannot access callback function when using webpack

我正在使用Webpack使用Google Maps构建一个小项目,但是由于Webpack构建脚本的方式,我在Google达到回调函数方面遇到了问题。 我可以使Google达到回调函数的唯一方法是将其手动移入Webpack构建的全局范围。 我想知道是否仍然可以用不同的方式编写它,这样我就不需要手动更改捆绑的文件。

预先建立:

import {apiKey} from './apiKey';

document.addEventListener('DOMContentLoaded', function(){

let lang;

if(document.querySelectorAll('#map').length > 0){
    if(document.querySelector('html').lang){
        lang = document.querySelector('html').lang;
    } else {
        lang = "en";    
    }

    let js_file = document.createElement('script');
    js_file.type = "text/javascript";
    js_file.src = 'https://maps.googleapis.com/maps/api/js?callback=initMapCallback&signed_in=true&key=' + apiKey + '&language=' + lang;
    document.getElementsByTagName('head')[0].appendChild(js_file);
};



});

   let map ;

   function initMapCallback() {
      map = new google.maps.Map(document.getElementById("map"), {
         center: {lat: -34.397, lng: 150.644},
         zoom: 8
      });
   ;

构建后:

/* 0 */
/***/ function(module, exports, __webpack_require__) {

'use strict';

var _apiKey = __webpack_require__(1);

var map = void 0;

function initMapCallback() {
    map = new google.maps.Map(document.getElementById("map"), {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 8
    });
};

document.addEventListener('DOMContentLoaded', function () {

    var lang = void 0;

    if (document.querySelectorAll('#map').length > 0) {
        if (document.querySelector('html').lang) {
            lang = document.querySelector('html').lang;
        } else {
            lang = "en";
        }

        var js_file = document.createElement('script');
        js_file.type = "text/javascript";
        js_file.src = 'https://maps.googleapis.com/maps/api/js?callback=initMapCallback&signed_in=true&key=' + _apiKey.apiKey + '&language=' + lang;
        document.getElementsByTagName('head')[0].appendChild(js_file);
    };
});

  /***/ },
  /* 1 */
 /***/ function(module, exports) {

'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
var apiKey = exports.apiKey = 'something';

/***/ }
/******/ ]);

当您在IIFE中使用webpack时,所有代码都在全局范围之外运行。 如果要显式提供某些内容,可以将其自己附加到窗口。

只需在函数定义之后添加以下内容:

window.initMapCallback = initMapCallback;

或一行执行:

window.initMapCallback = function initMapCallback() { /* ... */ };

就是这样!

暂无
暂无

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

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