R
R
Richard Hendrix2018-08-25 19:28:14
Node.js
Richard Hendrix, 2018-08-25 19:28:14

How to implement "hot" rendering of components in React using Webpack using this code example?

I can’t figure out what the error is, I’ve already rummaged through a bunch of tutorials.
It gives me only the public folder and everything in it, although the compilation of the bundle runs normally with every change in the files. That is, as a result, if the bundle is in public, it displays it, and if not, then empty html.
webpack: 4.16.4
webpack-dev-middleware: 3.2.0
webpack-hot-middleware: 2.22.3
react: 16.4.2
babel-core: 6.26.3
server.js

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

const app = express();

const webpackConfig = require('../webpack.config.dev');
const webpack = require('webpack');

const compiler = webpack(webpackConfig);

app.use(
  require('webpack-dev-middleware')(compiler, {
      noInfo: true,
      publicPath: webpackConfig.output.publicPath
  })
);

app.use(require('webpack-hot-middleware')(compiler));

app.use(express.static('public'));

app.get('/', (req, res) =>
  res.sendFile(path.resolve(__dirname, './public/index.html'))
);

app.listen(3000, () => console.log('App listening on port 3000!'));

webpack.config.dev.js
const webpack = require("webpack");
const path = require("path");

module.exports = {
    entry: {
        index: [
            "webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000",
            "./src/index.js"
        ]
    },
    output: {
        path: path.resolve(__dirname, "./public/js"),
        filename: "[name].bundle.js",
        publicPath: "/"
    },
    plugins: [new webpack.HotModuleReplacementPlugin()],
    module: {
        rules: [
            {
                test: [/\.js$/, /\.jsx$/],
                exclude: /node_modules/,
                include: path.join(__dirname, 'src'),
                use: 'babel-loader',
            }
        ]
    }
};

.babelrc
{
  "presets": [
    "env",
    "es2015",
    "react",
    "stage-0"
  ],
  "plugins": [
    "react-hot-loader/babel"
  ]
}

./src/index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import App from './App.jsx'

const render = Component => {
    ReactDOM.render(
        <AppContainer>
            <Component />
        </AppContainer>,
        document.getElementById('root'),
    )
}

render(App)

if (module.hot) {
    module.hot.accept('./App.jsx', () => {
        const NextApp = require('./App.jsx').default;
        render(NextApp)
    })
}

./src/App.jsx
import React from 'react'
import { hot } from 'react-hot-loader'

const App = () => <div>Hello World!</div>

export default hot(module)(App)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question