请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

读取编码为base64格式的

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;其实是读取的对的,但是会报

//img1.sycdn.imooc.com//szimg/5a5acd8c0001080023601168.jpg

好吧,原来是视频没看完

正在回答 回答被采纳积分+3

1回答

Jokcy 2018-01-14 11:38:31

好的。

0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号