如何在Google Maps API中使用Webpack?

问题描述:

我正在使用Webpack + html-webpack-plugin来构建我所有的静态文件。问题是,当我将它与Google Maps API一起使用时,它不起作用。如何在Google Maps API中使用Webpack?

我有这样的代码:

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不是一个函数'。我查看了输出内部,看起来initMap不是作为全局函数声明的,而是作为模块内部的函数或类似的东西声明的,所以也许就是这个问题。

我应该如何使用Google Maps API和webpack?我知道我可以将一些库与我的脚本捆绑在一起,比如反应,我应该这样做吗?这里应该采取什么方法?

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> 
+0

谷歌地图API不包装与webpack你应该保持作为外部来源,如果失败,这是因为script.js没有打包,或者你不使用你的新包装的js。请向我们展示您的webpack配置,并且您的最终html文件 –

+0

@DanyelDarkcloud更新了问题 – serge1peshcoff

在的script.js

你的函数声明之后,该功能添加到全球范围内,像这样:

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

是的,它做到了,非常感谢! – serge1peshcoff