Горячая замена модулей (HMR) не работает в приложении React - PullRequest
0 голосов
/ 23 февраля 2020

Я не использую React Hot Loader, просто Webpack HMR, поскольку RHL не настолько стабильный или надежный tmk.

Так что у меня есть это в моем index.jsx:

ReactDOM.render(
  <Root store={store} onEnterRedir={onEnterRedir}/>,
  document.getElementById('app')
);

if (module.hot) {
  console.log('the module IS hot');   // this works, it gets logged
  module.hot.accept('./root.jsx', () => {
    console.log('the module was reloaded.');  // this never gets logged
    const NextRootContainer = require('./root.jsx').default;
    render(<NextRootContainer onEnterRedir={onEnterRedir} store={store}/>, document.getElementById('app'));
  })
}

так как мои комментарии кода говорят - модуль горячий, но "the module was reloaded" никогда не регистрируется ... вот моя команда webpack:

NODE_ENV=development webpack --mode development --hot --config 'webpack.config.dev.js' --progress --colors --watch

и вот моя конфигурация webpack:

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

// plugins
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); // this replaces the ExtractTextPlugin
const ManifestRevisionPlugin = require('manifest-revision-webpack-plugin');

module.exports = {
  mode: 'development',

  entry: {
    // dash: ['react-hot-loader/patch','./src/index.jsx', './style/dash/index.scss'],
    // marcom: ['react-hot-loader/patch','./src/marcom.js', './style/marcom/index.scss'],
    dash: ['./src/index.jsx', './style/dash/index.scss'],
    marcom: ['./src/marcom.js', './style/marcom/index.scss'],
  },

  output: {
    path: path.join(__dirname, 'public'),
    publicPath: '/',
    filename: 'js/[name].js',
  },

  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          name: 'common',
        },
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendor',
          enforce: true,
          chunks: 'initial',
          // FIXME: do we add chunks & minChunks here?
        },
      },
    },
  },

  module: {
    rules: [
      {
        test: /\.jsx?$/, // this matches both js and jsx files
        exclude: /(node_modules|bower_components)/, // this is how babel recommends doing it
        use: [{
          loader: 'babel-loader', // the options for this are specified in .babelrc
          options: {
            plugins: [
              "transform-object-rest-spread",
              "transform-class-properties",
              // 'react-hot-loader/babel' // TODO
            ]
          }
        }]
      },
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
        ],
      },
      {
        test: /\.scss$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          {
            loader: 'sass-loader',
            options: {
              includePaths: [
                path.resolve(__dirname), // FIXME: not sure if this is actually needed
              ],
            },
          },
        ],
      },
      {
        test: /\.(gif|png|jpe?g|svg)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[name]-[hash].[ext]',
              outputPath: 'img/',
              publicPath: '/img/',
            },
          },
          'image-webpack-loader',
        ],
      },
    ],
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env.cm_api_host': JSON.stringify(process.env.cm_api_host || 'localhost'),
      'process.env.NODE_ENV': JSON.stringify('development'),
      'process.env.DEBUG': JSON.stringify(process.env.DEBUG || 'false')
    }),
    new MiniCssExtractPlugin({ filename: 'css/[name].css' }),
    new ManifestRevisionPlugin(path.join('assets.json'), {
      rootAssetPath: './img',
      ignorePaths: ['.DS_Store'],
      extensionsRegex: /\.(jpe?g|png|gif|svg)$/i,
    }),
  ],

  resolve: {
    modules: [
      'node_modules',
      path.resolve(__dirname, 'src'),
      path.resolve(__dirname, 'img'),
    ],
    extensions: ['.js', '.jsx', '.css', '.scss'],
    alias: {
      // 'react-dom': '@hot-loader/react-dom',
      numeral: 'numbro'
    },
  },

  node: {
    console: true,
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
  },

  devtool: false,

  context: __dirname,
};

Кто-нибудь знает, что здесь может пойти не так?

...