使用webpack时,Google地图无法访问回调功能

时间:2016-07-29 14:41:17

标签: javascript google-maps callback webpack

我正在使用webpack使用谷歌地图构建一个小项目,因为webpack构建脚本的方式,我遇到谷歌到达回调函数的问题。我可以让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';

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

1 个答案:

答案 0 :(得分:2)

在IIFE中使用webpack时,所有代码都在全局范围之外运行。如果你想明确地提供一些东西,你可以自己将它附加到窗口。

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

window.initMapCallback = initMapCallback;

或者在一行中完成:

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

就是这样!