Babel.js 使用Webpack构建后未定义窗口

wkyowqbh  于 2023-08-01  发布在  Babel
关注(0)|答案(3)|浏览(149)

我正在开发一个reactJS应用程序,我也在使用WebPack 4.29.6我在这里面临的问题是,当我运行npm run dev命令时,它在本地运行一切都很完美,而当我想在服务器上部署时,我不知道如何做,我正在使用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,
  },
});

eaf3rand

eaf3rand1#

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

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

字符串
您可以在这里看到有关here和有关globalObject设置的Webpack文档中讨论的问题。

20jt8wwn

20jt8wwn2#

使用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
  }
}

字符串

qmelpv7a

qmelpv7a3#

在尝试构建docusaurus文档时,我遇到了相同的错误。要在不修改内部代码的情况下解决这个问题,我建议在位于src/theme/Root.jsRoot.js文件中执行简单的检查(如果不存在,则直接创建它)。您可以添加以下代码段:

...
export default function Root({ children }) {
  if (typeof window !== "undefined") {
    return (
      <>
        {children} 
      </>
    );
  }
  return null;
}

字符串
通过实现此检查,可以确保在应用程序运行之前定义了窗口对象,从而防止错误。

相关问题