J
J
J. Snow2022-02-03 19:13:51
Express.js
J. Snow, 2022-02-03 19:13:51

How to screw React Hot Module Reload?

Hey!
There is such a React project:

package.json

{
  "main": "dist/server.js",
  "scripts": {
    "build:app": "webpack --config ./webpack.app.config.js",
    "build:server": "webpack --config ./webpack.server.config.js",
    "start": "node ."
  },
  ...
}


yarn build:app builds the React app into the final dist/app.js file :

webpack.app.config.js
module.exports = {
  entry: ['./src/app.tsx'],
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx'],
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  output: {
    filename: 'app.js',
    path: path.resolve(__dirname, 'dist'),
  },
}


yarn build:server runs a server build that gives the web app and also provides some additional API:

webpack.server.config.js
module.exports = {
  target: 'node',
  entry: './src/server.tsx',
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx'],
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  output: {
    filename: 'server.js',
    path: path.resolve(__dirname, 'dist'),
  },
}

server.tsx
const app = express()

app.use(express.static(path.resolve('dist')))

app.get('/my-api', (req, res) => {
  // ...
})

app.get('*', (req: Request, res: Response) => {
  res.set('Content-Type', 'text/html')

  res.send(
    `<!doctype html>${renderToString(
      <html>
        <head>
          <meta charSet="utf-8" />
          <title />
          <meta
            name="viewport"
            content="initial-scale=1.0, maximum-scale=1.0"
          />
        </head>
        <body>
          <div id="root" />

          <script src="/app.js" />
        </body>
      </html>,
    )}`,
  )
})

app.listen(3050)


The project is started with the yarn start command .

TASK:

Screw HMR.
So that you can update app.js on the fly and the application is also updated without having to restart everything.

HMR on the server side is optional. In server.js, changes are infrequent.

How to implement it?

Next.js do not offer :))

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