Webpack 热重载问题

问题描述 投票:0回答:2

我使用的是 webpack 3,没有热重载问题,然后我升级到了 webpack 5。

Webpack 版本:^5.50.0,React 版本:17.0.2

我的热重载无法正常工作。当状态 ve 属性更改时,它会刷新页面并转到主目录。

这是我用于开发的 webpack 热配置;

const webpack = require('webpack') //to access built-in plugins
const HtmlWebpackPlugin = require('html-webpack-plugin') //installed via npm
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const CopyPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const vendorArray = require('./vendors')
const path = require('path')
const Dotenv = require('dotenv-webpack')

module.exports = {
  mode: 'development',
  devtool: 'source-map',
  entry: {
    main: [
      'react-hot-loader/patch',
      'webpack-dev-server/client?http://0.0.0.0:3002',
      'webpack/hot/only-dev-server',
      './src/main.js'
    ]
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[hash:8].js'
  },
  resolve: {
    extensions: ['.js', '.jsx', '.css', '.scss', '.json']
  },
  module: {
    rules: [
      {
        test: /\.js?$/,
        exclude: /(node_modules|bower_components)/,
        loader: './config/webpack/style-loader'
      },
      {
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [['@babel/preset-env', { targets: 'defaults' }], '@babel/preset-react'],
            plugins: [
              '@babel/plugin-transform-runtime',
              '@babel/plugin-proposal-class-properties',
              '@babel/plugin-proposal-optional-chaining',
              '@babel/plugin-proposal-nullish-coalescing-operator',
              [
                '@babel/plugin-proposal-decorators',
                {
                  legacy: true
                }
              ]
            ]
          }
        }
      },
      {
        test: /\.(sa|sc|c)ss$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader']
      },
      {
        test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)([\?]?.*)$/,
        type: 'asset/resource'
      }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      APP_ENV: JSON.stringify('dev')
    }),
    new HtmlWebpackPlugin({
      template: './public/index.html',
      templateParameters: {
        recaptchaSiteKey: '6LfbRrEZAAAAAL1EiyUSq1yzEw1xqleak2xC2pzi',
        intranetLogin: true
      }
    }),
    new MiniCssExtractPlugin(),
    new Dotenv({
      path: path.resolve(__dirname, './../../.env.test')
    })
  ]
}

这是server.js

var webpack = require('webpack')
var config = require('./config/webpack/webpack-hot.config')
var WebpackDevServer = require('webpack-dev-server')

const stats = {
  assets: true,
  children: false,
  chunks: false,
  hash: false,
  modules: false,
  publicPath: false,
  timings: true,
  version: false,
  warnings: true,
  colors: { green: '\u001b[32m' }
}


config.plugins.push(
  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: JSON.stringify('development'),
      TARGET: '"web"'
    }
  })
)

process.env.BABEL_ENV = 'dev'
new WebpackDevServer(webpack(config), {
  hot: true,
  contentBase: __dirname,
  publicPath: '/',
  compress: true,
  historyApiFallback: true,
  stats: stats,
  port: 3002,
  host: '0.0.0.0',
  proxy: {
    '/auth/*': {
      target: 'blablabla',
      secure: false,
      onProxyRes: removeCookiePath,
      changeOrigin: true
    },
    '/api/cti/*': {
      target: 'blablabla',
      secure: false,
      onProxyRes: removeCookiePath,
      changeOrigin: true
    },
    '/api/abc/*': {
      secure: false,
      target: 'https://blabla',
      changeOrigin: true
    }
  }
}).listen(3002, '0.0.0.0', function(err, result) {
  if (err) {
    console.log(err)
  }
  console.log('Listening at http://127.0.0.1:3002')
  console.log('webpack is bundling, please wait...')
})
reactjs webpack hot-reload
2个回答
0
投票
Webpack 5 中不再支持您应用的

属性

contenBase
。而是使用
static
:

devServer: {
      port: 8080,
      hot: "only",
      static: {
        directory: path.join(__dirname, './'),
        serveIndex: true,
      },
    },

0
投票

就我而言,我添加了

ReactRefreshPlugin
并且它起作用了

const webpack = require('webpack');
const ReactRefreshPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
// ...

config.plugins.push(
    new ReactRefreshPlugin(),
    new webpack.HotModuleReplacementPlugin(),
);
© www.soinside.com 2019 - 2024. All rights reserved.