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

Google Maps cannot access callback function when using webpack

本文关键字:访问 回调 功能 谷歌地图 webpack 使用      更新时间:2023-09-26

我正在使用webpack使用谷歌地图构建一个小项目,由于webpack构建脚本的方式,我在谷歌访问回调函数时遇到了问题。我能让谷歌访问回调函数的唯一方法是手动将其移动到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() { /* ... */ };

就这样!