鍍金池/ 問答/HTML/ 請問配置完 HMR,console 中消息因何重復(fù)打印?

請問配置完 HMR,console 中消息因何重復(fù)打?。?/h1>

圖片描述

如圖,想請問因何產(chǎn)生了這種情況,VM1160__log.js:23 與 log.js: 23 各自打印一遍

或者也可以說,VM 為何會多開了這么一條 socket,該如何解決?

新版本 create-react-app 已經(jīng)可以通過在 index.js 加入下面語句,開啟不保留狀態(tài)的 HMR 模式

if (module.hot) {
  module.hot.accept();
}

在執(zhí)行 eject 后嘗試看過源碼,直到目前還沒看出個所以然來

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { AppContainer } from 'react-hot-loader';


if (module.hot) {
  module.hot.accept();
}

ReactDOM.render(
  <AppContainer>
    <App name='igoist' />
  </AppContainer>,
  document.getElementById('app')
);

webpack.config.js

/* global __dirname */
const path = require('path');
// const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const publicPath = '/';

module.exports = [
  {
    devtool: 'eval',

    entry: {
      index: [
        'react-hot-loader/patch',
        // 'webpack/hot/only-dev-server', // It's removed in latest version ?
        path.resolve(__dirname, 'src/index.js'),
      ]
    },

    output: {
      filename: '[name].bundle.min.js',
      path: path.resolve(__dirname, 'dist/'),
      publicPath
    },

    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loaders: ['babel-loader', 'eslint-loader'],
          include: [path.join(__dirname, publicPath + 'src')]
        },
      ]
    },

    plugins: [
      // new webpack.optimize.UglifyJsPlugin({
      //   compress: {
      //       warnings: false
      //   }
      // })
      new HtmlWebpackPlugin({
        template: __dirname + '/public/index.html'
      }),
      // new webpack.HotModuleReplacementPlugin() // if the '--hot' option has been indicated, then you don't need this one
      // new webpack.DefinePlugin({
      //   'process.env': {
      //     'NODE_ENV': '"production"'
      //   }
      // })
    ],

    devServer: {
      contentBase: './dist',
      port: 1188,
      publicPath,
      // historyApiFallback: true,
      inline: true,
      // hot: true,  // 這參數(shù)與 --hot 與插件 3 者間關(guān)系 -- now 'hot' is deprecated
      hotOnly: true
    }
  },
];

使用了非 Node 的方式配置了 HMR,在 html 模板中引入了相應(yīng) bundle

回答
編輯回答
葬愛

自問自答。

年假休息了一星期,重新開始寫代碼

重新起了個新的項(xiàng)目模板,一對比,很快就想到了原因

還記得 HtmlWebpackPlugin 嗎?

Bug 所在:/public/index.html 中手動引入了 index.bundle.min.js

太粗心了

2017年9月8日 17:05
編輯回答
吃藕丑

很顯然,你在這里執(zhí)行了兩遍render:

if (module.hot) {
  module.hot.accept(() => {
    render(); // 這是第2遍
  });
}

const render = () => {
  ReactDOM.render(
    <AppContainer>
      <App name='igoist' />
    </AppContainer>,
    document.getElementById('app')
  );
};

render(); // 這是第1遍
2017年2月26日 15:19