React源码学习:fiber 调试环境搭建/ssr/client/server

从0搭建一个client/server 的react项目,支持SSR(P34-37)
更新于: 2022-06-02 15:46:45

思维导图

基本的项目结构图

目录结构

.
├── babel.config.js
├── build
│   └── server.js
├── dist
│   ├── bundle.js
│   └── bundle.js.map
├── package-lock.json
├── package.json
├── src
│   ├── client.js
│   └── server.js
├── webpack.config.client.js
└── webpack.config.server.js

安装

npm i -D webpack webpack-cli webpack-node-externals
npm i -D @babel/core @babel/preset-env @babel/preset-react babel-loader nodemon
npm i -D npm-run-all
npm i -D express

server 端三步曲

步骤代码备注
01-webpack.server.config.js
const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  target: 'node',
  mode: 'development',
  entry: './src/server.js',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'server.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  },
  // 不要打包 node_modules 下的文件
  externals: [nodeExternals()]
};
打包server.js 为es5格式
02-server.js 基本代码
import express from 'express';

const app = express();

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

const template = `
  <html>
    <head>
        <title>React Fiber</title>
    </head>
    <body>
        <div id="root"></div>
    </body>
  </html>
`;

app.get('*', (req, res) => {
  res.send(template);
});

app.listen(3000, () => {
  console.log('Server is running.');
});
基本的ssr模板代码
03-package.json
"scripts": {
  "dev:server-compile": "webpack --config webpack.config.server.js --watch",
  "dev:server": "nodemon ./build/server.js",
  "start": "npm-run-all -p dev:*"
}
基本的server端命令

client 三步曲

步骤代码备注
01-webpack.client.config.js
const path = require('path');

module.exports = {
  target: 'web',
  mode: 'development',
  entry: './src/client.js',
  devtool: 'source-map',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  }
};
打包bundle.js 为es5格式
02-server.js 基本代码
import express from 'express';

const app = express();

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

const template = `
  <html>
    <head>
        <title>React Fiber</title>
    </head>
    <body>
        <div id="root"></div>
        <script src="bundle.js"></script>
    </body>
  </html>
`;

app.get('*', (req, res) => {
  res.send(template);
});

app.listen(3000, () => {
  console.log('Server is running.');
});
基本的ssr模板代码
03-package.json
"scripts": {
  "dev:server-compile": "webpack --config webpack.config.server.js --watch",
  "dev:server": "nodemon ./build/server.js",
  "start": "npm-run-all -p dev:*",
  "dev:client-compile": "webpack --config webpack.config.client.js --watch"
}
基本的npm命令
04. client.js
console.log('hello react client.')
测试client代码

参考