Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add ReactJS to existing node.js backend app

I have a very simple node.js API

Structure:

| project-name
|  public
|     index.html
|     ... some static js/css
|  app.js
|  package.json

app.js

var express = require('express'),
  bodyParser = require('body-parser'),
  http = require('http');

var app = module.exports = express();
app.set('port', process.env.PORT || 8000);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static(path.join(__dirname, 'public')));

app.route('/api/projects').get(...).post(...)
app.route('/api/sales').get(...).post(...)

app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// Starting express server
http.createServer(app).listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
});

Run server - node app.js

Notice: It's a learning project, not for production. I just want to figure out how it all work together.

And now I want to add ReactJS to this project (actualy to public/index.html). But I still want to use app.js to run server with it's api, with the same port.

I know how to make "production build" (compile all jsx to js and use as simple scripts). My questions is only about dev server.

I want:

  • To run a server (api) and client (reactjs) with only one command (node app.js or nodemon app.js etc)
  • To have an auto-reload after script changes (seems nodemon can do it)
like image 720
Vadym Avatar asked Nov 08 '22 17:11

Vadym


1 Answers

To make both run with single command you can add command like:

"start": "cross-env NODE_ENV=development npm run webpack --env.browser && cross-env NODE_ENV=development npm run webpack -- --env.server && NODE_ENV=development node compiled/server.dev.js",

Then run command npm run start

And to watch all the directory changes you should add directory name in nodemon.json file like:

{
    "verbose": false,
    "watch": [
      "app/utils",
      "app/routes.jsx",
      "server",
      "webpack"
    ],
    "exec": "npm run start && node server.dev.js"
}
like image 135
Abhishek Jain Avatar answered Nov 14 '22 21:11

Abhishek Jain