读取编码为base64格式的

来源:2-8 开发时的服务端渲染

慕用8116058

2018-01-14

const axios = require('axios');
const webpack = require('webpack');
const path = require('path');
const MemoryFs = require('memory-fs');
const ReactDOMServer = require('react-dom/server');

const rootDir = path.join(__dirname, '../..');

const serverConfig = require(path.join(rootDir, 'build/webpack.config.server.js'));

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

const mfs = new MemoryFs();
const Module = module.constructor;

let serverBundle;

const serverCompiler = webpack(serverConfig);
serverCompiler.outputFileSystem = mfs;
serverCompiler.watch({}, (err, state) => {
  if (err) {
    throw err;
  }
  state = state.toJson();
  state.errors.forEach(console.error);
  state.warnings.forEach(console.warn);

  const bundlePath = path.join(
    serverConfig.output.path,
    serverConfig.output.filename
  );

  const bundle = mfs.readFileSync(bundlePath, 'utf-8');
  console.log(bundle);

  const m = new Module();
  m._compile(bundle);
  serverBundle = m.exports.default;
});


module.exports = function (app) {
  app.get('*', function (req, res) {
    getTemplate().then((template) => {
      const content = ReactDOMServer.renderToString(serverBundle);
      res.send(template.replace('<!--app-->', content));
    })
  })
};

这里和老师的代码完全一致;但是打印(console.log(bundle);)的结果是base64编码的,导致运行报错,一直没找到原因。

哦,我知道了,我加了一个devtool:inline-source-map;其实是读取的对的,但是会报

//img.mukewang.com/szimg/5a5acd8c0001080023601168.jpg

好吧,原来是视频没看完

写回答

1回答

Jokcy

2018-01-14

好的。

0
0

React全栈+服务器渲染(ssr)打造社区Webapp

【毕设面试】只会写业务代码?out了,带你学会搭建属于自己的工程!

768 学习 · 414 问题

查看课程