使用Webpack构建后未定义窗口

时间:2019-04-25 12:23:32

标签: reactjs webpack babel

我正在开发reactJS应用程序,而且我正在使用 WebPack 4.29.6 ,这里我面临的问题是,当我运行 npm run dev < / b>命令,而当我想在服务器中部署时,我不知道该怎么做,我正在使用 build:production 命令构建应用程序,然后它会在其中生成/ dist文件夹,其中包含所有文件在这里,我尝试运行 bundle.js ,它给了我这个错误: ReferenceError:窗口未定义

这些是我用来启动应用程序的命令:

"scripts": {
    "dev": "cross-env webpack-dev-server --config ./webpack.config.dev.js --mode development",
"build:production": "cross-env webpack --config webpack.config.production.js --mode production"
}

这是我的webpack.config.common.js

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

const outputPath = path.join(__dirname, '/dist');

const port = process.env.PORT || 4000;

module.exports = {
  context: __dirname,
  entry: './src/index.jsx',
  resolve: {
    extensions: ['*', '.js', '.jsx'],
  },
  output: {
    path: outputPath,
    publicPath: '/',
    filename: 'bundle.js',
    sourceMapFilename: 'bundle.map',
  },
  devServer: {
    port,
    historyApiFallback: true,
    compress: true,
    contentBase: './dist',
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader', 'eslint-loader'],
      },
      {
        test: /\.less$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
          },
          {
            loader: 'less-loader',
          },
        ],
      },
      {
        test: /\.css$/,
        use: ['css-loader'],
      },
      {
        test: /\.svg$/,
        loader: 'svg-inline-loader',
      },
      {
        test: /\.(png|jpg|gif|woff(2)?|ttf|eot|svg)$/,
        exclude: [
          /\.(js|jsx|mjs)$/,
          /\.html$/,
          /\.json$/,
          /\.(less|config|variables|overrides)$/,
        ],
        use: [
          {
            loader: 'file-loader',
          },
        ],
      },
    ],
  },
  plugins: [
    new webpack.ProvidePlugin({
      Promise: 'es6-promise-promise',
    }),
  ],
};

这是我的webpack.config.dev.js

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

const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpackCommonConfig = require('./webpack.config.common');

module.exports = merge(webpackCommonConfig, {
  mode: 'development',
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, '/index.html'),
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.EnvironmentPlugin({ NODE_ENV: 'development' }),
  ],
  devtool: 'inline-source-map',
  devServer: {
    hot: true,
    open: true,
  },
  externals: {
    // global app config object
    config: JSON.stringify({
      apiUrl: 'http://localhost:3000',
    }),
  },
});

这是我的webpack.config.production.js

const webpack = require('webpack');
const merge = require('webpack-merge');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

const webpackCommonConfig = require('./webpack.config.common');

module.exports = merge(webpackCommonConfig, {
  mode: 'production',
  plugins: [new webpack.EnvironmentPlugin({ NODE_ENV: 'production' })],
  optimization: {
    minimizer: [
      // we specify a custom UglifyJsPlugin here to get source maps in production
      new UglifyJsPlugin({
        cache: true,
        parallel: true,
        uglifyOptions: {
          compress: false,
          ecma: 6,
          mangle: true,
        },
        sourceMap: true,
      }),
    ],
  },
  devtool: 'source-map',
  devServer: {
    compress: true,
  },
});

2 个答案:

答案 0 :(得分:0)

回答也许晚了,但可能会帮助别人。我还遇到了Webpack 4的ReferenceError: window is not defined.问题,发现在Webpack配置文件的globalObject: 'this'部分中添加了output行解决了我的问题:

  output: {
    globalObject: "this",
    filename: "[name].js",
    path: path.join(__dirname, "build/package"),
    publicPath: "/resources/",
  }

您可以看到问题已得到讨论here 以及有关globalObject设置here的Webpack文档。

答案 1 :(得分:0)

使用 global 对我有用。

const window = global.window
if (window && window.localStorage) {
  const storageLogLevel = window.localStorage.getItem(LOG_LEVEL_KEY)
  switch (storageLogLevel) {
    case LogLevel.DEBUG:
      logLevel = 0
      break
    case LogLevel.INFO:
      logLevel = 1
      break
    case LogLevel.WARNING:
      logLevel = 2
      break
    case LogLevel.CRITICAL:
      logLevel = 3
      break
    default:
      logLevel = 1
  }
}