I have been using Webpack along with the html-webpack-plugin to compile all my static files. However, I am facing an issue when integrating it with the Google Maps API.
Here is the code snippet:
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
// Other relevant code here
}
And here is a sample HTML file:
<!doctype html>
<html>
<head>
</head>
<body>
<div id="map"></div>
<script async="async" defer="defer"
src="https://maps.googleapis.com/maps/api/js?key=<token here>&callback=initMap">
</script>
<script src="script.js"></script>
</body>
</html>
When I run this standalone HTML file, everything works perfectly. But when I try to run it through webpack, I receive an error stating 'initMap is not a function'. Upon inspecting the output, I noticed that initMap is being declared as a function within a module rather than globally, which might be causing the problem.
What would be the correct approach to use the Google Maps API with webpack? Should I bundle some libraries like react in my script as well? Any guidance on how to resolve this issue would be greatly appreciated.
Update: Included below is my webpack.config.js for reference:
/* eslint-disable */
const path = require('path')
const fs = require('fs')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
// More config details here...
The resulting HTML output looks like this (I've made some alterations for readability):
<!doctype html>
<html>
<head>
</head>
<body>
<a href="/login/facebook">Login</a>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCGSgj5Ts10UdapzUnWlr34NS5cuoBj7Wg&callback=initMap">
</script>
<script type="text/javascript" src="script.js"></script></body>
</html>