开发时的服务端渲染

$npm i axios -S             //
$npm i memory-fs -D    //内存中读写文件
$npm i http-proxy-middleware -D  //express中间件,做代理用
//server.js
const isDev=process.env.NODE_ENV==="development";

if(!isDev){
  const serverEntry=require('../dist/server-entry').default;
  const template=fs.readFileSync(path.join(__dirname,"../dist/index.html"),'utf-8');
  app.use('./public',express.static(path.join(__dirname,"../dist")));
  app.get('*',function(req,res){
    const appString=ReactSSR.renderToString(serverEntry);
    res.send(template.replace(''),appString);
  })
}else{
  //这里的内容比较多,另起一个文件==>==>==>==>==>==>====>
  const devStatic=require('./util/dev-static.js')    |
}                                                    |
                                                     |
//server文件夹下新建util->dev-static.js  <==<==<==<==<==
const path=require('path');
const axios=requite('axios');
const webpack=require('webpack');
const MemoryFs=require('memory-fs');
const proxy=require('http-proxy-middleware');
const ReactDomServer=require('react-dom/server');
const serverConfig=require('../../build/webpack.config.server');

const getTemplate=()=>{
  return new Promise((resolve,reject)=>{
    axios.get('http://localhost:3000/public/index.html')
    .then(res=>{
      resolve(res.data)})
    })
    .catch(reject)
}
const Module=module.constructor;

const mfs=new MemoryFs;
const serverCompiler=webpack(serverConfig);
serverCompiler.outputFileSystem=mfs;  //通过mfs读写文件
let serverBundle;
serverCompiler.watch({},(err,stats)=>{
  if(err)throw err;
  stats=stats.toJson();
  stats.errors.forEach(err=>console.error(err));
  stats.warnings.forEach(err=>console.warn(warn));
  const bundlePath=path.join(
    serverConfig.output.path,
    serverConfig.output.filename
  );
const bundle=mfs.readFileSync(bundlePath,'utf-8');
//以mfs启动将不会在硬盘中生成dist目录

const m=new Module();
m._compile(bundle,'server-entry.js');//编译时,需要指定文件名
serverBundle=m.exports.default;  //exports.default
})

module.exports=function(app){
  app.use('/public',proxy({
    target:'http://localhost:8888'
  }))
  app.get('*',function(req,res){
    getTemplate().then(template=>{
      const content=ReactDomServer.renderToString(serverBundle);
      res.send(template.replace('',content));
    })
  })
}
//package.json中修改script->start
"dev:server":"cross-env NODE_ENV=development node server/server.js"

你可能感兴趣的:(开发时的服务端渲染)