1

I am trying to set up my own boilerplate for creating react app just to know what is going on behind the scenes.

I am stuck at server rendering using Webpack/ Express/ react-router v4. Just don't know how to solve it.

My express.js file looks like this:

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);
})

What are the next steps to make it work? What I was thinking: 1. Define new entry in webpack.config.js for express.js 2. Fire up the express.bundle.js created by Webpack using node express.bundle.js

But as soon as I try to run webpack -p I get errors:

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 Answer 1

1

You should add target: 'node' to your webpack configuration file.

For more information, you can read at https://webpack.js.org/concepts/targets/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.