javascript - 运行webpack部署配置时如何解决 'window is not defined'?

标签 javascript node.js reactjs google-maps-api-3 webpack

我正在尝试将 React + 服务器应用程序部署到 Heroku。总体目标是使用 Heroku dyno 作为通用服务器来提供静态 Assets ,并作为我的 React 应用程序的 API 端点。我正在编写部署配置来缩小并遇到错误。

它缩小了,但在 node dist/bundle.js 上它给出了以下错误。

ReferenceError: window is not defined

为了使用 googlemaps api,我有一个 Map 组件,它将全局窗口对象上的函数设置为 Map 组件中定义的 initMap()

并在 loadJS() 中引用 window.document 两次。

正在开发中,它运行良好。
我用这篇文章来帮助 Making Google Maps work with React

我怀疑窗口对象未定义,因为还没有浏览器提供窗口对象。

你能证实我的怀疑吗?需要什么来解决这个问题?

我的 package.json 文件中的脚本

  "scripts": {
      "start": "npm build && node dist/bundle.js",
      "dev-start": "babel-node server/buildScripts/server.js",
      "build":"webpack --config ./webpack.deployment.config.js",
      "test": "echo \"Error: no test specified\" && exit 1"
  },

webpack.deployment.config.js

const path = require('path');
const webpack = require('webpack');

module.exports = {
    devtool: 'source-map',

    entry: [
        './client/index.js'
    ],
  output: {
      path: path.join(__dirname, 'dist'),
      filename: 'bundle.js',
      publicPath: './dist/'
  },
  plugins: [
      new webpack.optimize.UglifyJsPlugin({
          minimize: true,
          compress: {
          warnings: false
      },
      sourceMap: true
    })
  ],
  module: {
      loaders: [{
          test: /.jsx?$/,
          loader: 'babel-loader',
          include: path.join(__dirname, 'client'),
          exclude: /node_modules/,
          query: {
              presets: ['es2015', 'react']
        }
    },
     { test: /\.css$/, loader: "style-loader!css-loader" },
     { test: /\.(jpg|png|svg)$/, use: 'file-loader'}
    ]
},
};

客户端/组件/Googlemaps.js

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { getGoogleGeoLocation } from '../actions/index.js'

class Map extends React.Component {
    constructor(props) {
        super(props);

    this.initMap = this.initMap.bind(this)
  }

  initMap() {
    if(!this.props.location.lat  ) {
         let map = new google.maps.Map(this.refs.map, { center: { lat: 36.1699, lng: -115.1398 }, zoom: 12 });
    } else {
      let lat = parseFloat(this.props.location.lat)
      let lng = parseFloat(this.props.location.lng)
      let map = new google.maps.Map(this.refs.map, { center: { lat, lng }, zoom: 12 });
    }
 }

  componentDidMount() {
      window.initMap = this.initMap;
      loadJS('https://maps.googleapis.com/maps/api/js?key=AIzaSyAvn1WOC1uXO7jw820pYZsSzZUNh5g7cTs&callback=initMap')
      this.props.fetchLocation()
  }


  componentDidUpdate() {
    loadJS('https://maps.googleapis.com/maps/api/js?key=AIzaSyAvn1WOC1uXO7jw820pYZsSzZUNh5g7cTs&callback=initMap')
  }


  render() {
    const mapStyle = {
        width: 1000,
        height: 500,
    };
    if (this.props.hasErrored) {
        return <p>Sorry! There was an error loading the items</p>;
    }

    if (this.props.isLoading) {
        return (
            <div>
                <h4>loading...</h4>
                <div ref="map" style={mapStyle}></div>
           </div>
      );
    } else {  
        return (
            <div id='map' ref="map"></div>
        );
      }
    }
}

function loadJS(src) {
    var ref = window.document.getElementsByTagName("script")[0];
    var script = window.document.createElement("script");
    script.src = src;
    script.async = true;
    ref.parentNode.insertBefore(script, ref);
}


const mapStateToProps = (state) => {
    return {
        location: state.location,
        hasErrored: state.locationHasErrored,
        isLoading: state.locationIsLoading
    };
};

const mapDispatchToProps = (dispatch) => {
    return {
      fetchLocation: (url) => dispatch(getGoogleGeoLocation())
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(Map)

最佳答案

听起来您需要使用 npm 模块 jsdom,它在浏览器环境之外提供了一个 window/window.document 对象。

关于javascript - 运行webpack部署配置时如何解决 'window is not defined'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46326877/

相关文章:

javascript - 使用 GoLang http.FileServer 时找不到 React 脚本

javascript - 如何转换对象字段为 YYYY-DD-MM HH :MM:SS format into a list of lists? 的 JSON 文件

javascript - 我在这行代码中得到 "Type Error: Cannot read property of undefined"

Node.js 服务器对 HTTPS 的请求足以加密吗?

node.js - 未从 csslintrc 文件中获取 Mimosa csslint 配置

javascript - 如何在多个页面之间共享同一个 React 组件的状态?

javascript - Angular http.post 不通过订阅发送数据

javascript - 如何在javascript中有效匹配字符串中间的数字?

javascript - react | UseCallBack 内的 Prop 未在自定义 Hook 内更新

javascript - 使用CDN时如何调用react logger函数