如何在Google Maps API中使用Webpack?

ser*_*off 13 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
}
Run Code Online (Sandbox Code Playgroud)

还有一个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>
Run Code Online (Sandbox Code Playgroud)

如果我只运行这个文件,一切正常.但是,如果我运行它,webpack就会抱怨'initMap不是一个函数'.我查看了输出内部,似乎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
   })
 ],
}]
Run Code Online (Sandbox Code Playgroud)

输出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>
Run Code Online (Sandbox Code Playgroud)

小智 31

在script.js中

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

function initMap() {
    // Some stuff
}
window.initMap = initMap;
Run Code Online (Sandbox Code Playgroud)