ExpressJS + Webpack + react-router v4

时间:2017-07-23 16:52:39

标签: node.js reactjs express react-router server-side

我正在尝试设置我自己的样板来创建反应应用程序,只是为了知道幕后发生了什么。

我使用Webpack / Express / react-router v4陷入服务器渲染。只是不知道如何解决它。

我的express.js文件如下所示:

const express = require('express');
const morgan = require('morgan');
const path = require('path');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const StaticRouter = require('react-router').StaticRouter;
const App = require('./src/app');

const app = express();

// Views
app.set('view engine', 'ejs');
app.set('views', path.resolve(__dirname, 'src', 'templates'))

// Middlewares
app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));
app.use(express.static(path.resolve(__dirname, 'dist')));

// Paths
app.get('*', (req, res) => {
  const context = {}
  const html = ReactDOMServer.renderToString(
    <StaticRouter
      location={req.url}
      context={context}
    >
      <App/>
    </StaticRouter>
  )
  res.render('index', {reactOutput: html});
  // Then in my index.ejs put a <%- reactOutput %> 
});

const port = 8000;
app.listen(port, () => {
  console.log('Listening on port', port);
})

让它运作的下一步是什么?我在想什么: 1.在webpack.config.js中为express.js定义新条目 2.使用express.bundle.js

启动Webpack创建的node express.bundle.js

但是一旦我尝试运行webpack -p,我就会收到错误:

ERROR in ./node_modules/express/lib/request.js
Module not found: Error: Can't resolve 'net' in '/Users/NYC/Desktop/JavaScript/Boilerplate/client/node_modules/express/lib'

ERROR in ./node_modules/express/lib/view.js
Module not found: Error: Can't resolve 'fs' in '/Users/NYC/Desktop/JavaScript/Boilerplate/client/node_modules/express/lib'

ERROR in ./node_modules/send/index.js
Module not found: Error: Can't resolve 'fs' in '/Users/NYC/Desktop/JavaScript/Boilerplate/client/node_modules/send'

ERROR in ./node_modules/etag/index.js
Module not found: Error: Can't resolve 'fs' in '/Users/NYC/Desktop/JavaScript/Boilerplate/client/node_modules/etag'

ERROR in ./node_modules/destroy/index.js
Module not found: Error: Can't resolve 'fs' in '/Users/NYC/Desktop/JavaScript/Boilerplate/client/node_modules/destroy'

ERROR in ./node_modules/mime/mime.js
Module not found: Error: Can't resolve 'fs' in '/Users/NYC/Desktop/JavaScript/Boilerplate/client/node_modules/mime'

1 个答案:

答案 0 :(得分:1)

您应该将target: 'node'添加到您的webpack配置文件中。

有关详细信息,请参阅https://webpack.js.org/concepts/targets/