I use Webpack + html-webpack-plugin to create all my static files. The fact is that when I use it with the Google Maps API, it does not work.
I have this code:
var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 6 });
And the 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>
If I run this particular file, everything works fine. But if I ran this using webpack, his complaints about “initMap are not a function”. I looked at the result, and it seems that initMap is not declared as a global function, but as a function inside a module or something like that, so there may be a problem.
How should I use the Google Maps API with the web package? I know that I can link some libraries to my script, for example, to react, should I do the same? What should be the approach?
UPD: here is my webpack.config.js:
const path = require('path') const fs = require('fs') const webpack = require('webpack') const HtmlWebpackPlugin = require('html-webpack-plugin') const nodeModules = {} fs.readdirSync('node_modules') .filter(function(x) { return ['.bin'].indexOf(x) === -1 }) .forEach(function(mod) { nodeModules[mod] = 'commonjs ' + mod }) const htmlMinifierObj = { collapseWhitespace: true, removeComments: true } module.exports = [
And the HTML output (I removed the import of script.js from the source file because it added webpack and turned off minimization, just 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>