具有服务器端渲染功能的Webpack 4热加载

时间:2018-07-11 10:35:10

标签: javascript node.js reactjs webpack webpack-serve

我正在使用webpack v4.x,webpack-serve v2.x和React v16.x。

在开发过程中,我使用webpack-serve进行了热加载,但是现在我已经在应用中添加了服务器端渲染,所以我不明白如何使热加载再次起作用。

这是我的设置:

src / server.js

import { renderToString } from 'react-dom/server';
import express from 'express';
import path from 'path';
import React from 'react';

import App from './components/App';

const app = express();
app.use(express.static(path.resolve(__dirname, '../dist')));

app.get('/', (req, res) => res.send(`
  <!DOCTYPE html>
  <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>Test</title>
    </head>
    <body>
      <div id="app">${renderToString(<App />)}</div>
      <script src="/vendors~app.bundle.js" async defer></script>
      <script src="/app.bundle.js" async defer></script>
    </body>
  </html>
`));

app.listen(3000);

src / client.js

import { hydrate } from 'react-dom';
import React from 'react';

import App from './components/App';

const app = document.getElementById('app');
if (app) hydrate(<App />, app);

src / components / App / index.js

import React from 'react';

export default () => <div>Hello</div>;

webpack.config.js

const path = require('path');

module.exports = {
  mode: 'development',
  entry: {
    app: './src/client.jsx',
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  devtool: 'inline-source-map',
  serve: {
    host: '0.0.0.0',
    dev: {
      publicPath: '/dist/',
      logLevel: 'warn',
    },
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
    ],
  },
};

由于webpack-serve是一个相当新的东西,所以我很难找到带有服务器端渲染的安装示例。我发现了在服务器上将webpack-dev-middleware与webpack-dev-server一起使用的示例(尽管我实际上也无法正常工作)。

这里有几个问题: -webpack-serve是否在此处使用正确的东西,还是应该恢复为webpack-dev-server? -是否可以将webpack-serve集成到服务器端渲染设置中,如果可以,怎么办?

0 个答案:

没有答案