如何将Webpack与Google Maps API一起使用?

时间:2016-11-13 15:42:01

标签: javascript google-maps webpack html-webpack-plugin

我使用Webpack + html-webpack-plugin来构建我的所有静态文件。问题是,当我使用谷歌地图API时,它无法正常工作。

我有这段代码:

var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 6
  });
  // the other code, irrelevant
}

一个HTML文件:

<!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>

如果我只运行此文件,一切正常。但是如果我运行它,webpack就会抱怨initMap不是一个函数&#39;。我查看了输出内部,似乎initMap被声明为不是全局函数,而是作为模块中的函数或类似的东西,所以可能是问题。

我应该如何在webpack中使用Google Maps API?我知道我可以用我的脚本捆绑一些libs,比如反应,我应该这样做吗?这里的方法应该是什么?

UPD:这是我的webpack.config.js:

/* eslint-disable */
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 = [
// the first object compiles backend, I didn't post it since it's unrelated
{
 name: 'clientside, output to ./public',
 entry: {
   script: [path.join(__dirname, 'clientside', 'script.js')]
 },
 output: {
   path: path.join(__dirname, 'public'),
   filename: '[name].js'
 },
 module: {
   loaders: [
     {
       test: /\.js$/,
       loader: 'babel',
       query: { presets:['es2015', 'stage-0'] }
     }
   ],
 },
 plugins: [
   //new webpack.optimize.UglifyJsPlugin({minimize: true}),
   new HtmlWebpackPlugin({
     template: 'clientside/index.html',
     inject: 'body',
     chunks: ['script'],
     minify: htmlMinifierObj
   })
 ],
}]

输出HTML是(我已从我的源文件中删除导入script.js,因为它是由webpack添加的,并且为了便于阅读而关闭了最小化):

<!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>

1 个答案:

答案 0 :(得分:27)

在script.js

在函数声明之后,将函数添加到全局范围,如下所示:

function initMap() {
    // Some stuff
}
window.initMap = initMap;