我正在使用 webpack 使用 Google map 构建一个小项目,但由于 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() { /* ... */ };
就是这样!
关于javascript - 使用 webpack 时 Google map 无法访问回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38661579/