UnluckySerivelha
@UnluckySerivelha

Как победить «initMap is not a function» при использовании webpack и babel?

Привет. Пытаюсь использовать сборку webpack'ом с babel, но в таком случае почему-то не работает функция initmap для googlemaps.
Есть такой кусок разметки в конце html:
<script type="text/javascript" src="./js/bundle.js"></script>
<script type="text/javascript"  async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDgD9raCgCP3YPNgS7DZyoB8t-Q8wCuaRY&callback=initMap"></script>

Есть index.js, который является входной точкой для webpack:
//Google Maps init
function initMap() {
    var e = {
        lat: 40.714909,
        lng: -73.751213
    }
        , t = new google.maps.Map(document.getElementById("map"), {
        zoom: 16,
        center: e
    });
    new google.maps.Marker({
        position: e,
        map: t
    })
}
Но при транспиляции babel'ом он добавляет свой код в начало бандл-файла и получается так:
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = "./src/js/index.js");
/******/ })
/************************************************************************/
/******/ ({

/***/ "./src/js/index.js":
/*!*************************!*\
  !*** ./src/js/index.js ***!
  \*************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//Google Maps init
function initMap() {
    var e = {
        lat: 40.714909,
        lng: -73.751213
    },
        t = new google.maps.Map(document.getElementById("map"), {
        zoom: 16,
        center: e
    });
    new google.maps.Marker({
        position: e,
        map: t
    });
}

И в таком случае получается ошибка "initMap is not a function".
Если вынести функцию initMap в другой файл и подключить отдельно - всё в порядке, но хотелось бы, чтобы был один файл. В чем может быть проблема? Заранее спасибо.
  • Вопрос задан
  • 978 просмотров
Решения вопроса 1
rockon404
@rockon404
Frontend Developer
webpack.config.js
entry: 'entry.js',
output: {
  filename: 'bundle.js',
  library: 'App'
},


entry.js
function initMap() {
    var e = {
        lat: 40.714909,
        lng: -73.751213
    }
        , t = new google.maps.Map(document.getElementById("map"), {
        zoom: 16,
        center: e
    });
    new google.maps.Marker({
        position: e,
        map: t
    })
}

export {
  initMap,
};


в параметрах ссылки:
callback=App.initMap

Но если не используете в функции переменных из других частей кода, проще прописать функцию в теге script в html:
<script type="text/javascript" src="./js/bundle.js"></script>
<script>
//Google Maps init
function initMap() {
    var e = {
        lat: 40.714909,
        lng: -73.751213
    }
        , t = new google.maps.Map(document.getElementById("map"), {
        zoom: 16,
        center: e
    });
    new google.maps.Marker({
        position: e,
        map: t
    })
}
</script>
<script type="text/javascript"  async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDgD9raCgCP3YPNgS7DZyoB8t-Q8wCuaRY&callback=initMap"></script>
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы