2016-11-13 107 views
5

我正在使用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

回答

13

在的script.js

你的函數聲明之後,該功能添加到全球範圍內,像這樣:

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

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