Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack Dev Server + Express Web Server

I'm having trouble setting up a development workflow that will do both of the following tasks simultaneously:

  1. Recompile static assets (js, css) on file change. Serve these static assets. Notify the browser that the page must reload whenever assets are changed. Use react-hot-loader.
  2. Use express to run a server which serves an API which the static assets will "consume". Have this express server restart any time my server files change.

Is the best practice to have webpack-dev-server serve the static assets, and have a separate web server serve the API on a different port? If so, the API calls in the javascript will need to specify the host and port, and will need to be changed before going to production. It seems all the tutorials online focus on #1, and don't set up an API server. Can anyone point me in the correct direction?

I'm not opposed to using gulp and browserify or SystemJS instead of webpack, but it seems that if I want to use react-hot-loader, I need to use webpack.

like image 824
Dave Avatar asked Nov 06 '15 21:11

Dave


1 Answers

You can do something like this:

  • Create an express() proxy
  • Create a webpack-dev-server
  • Link the assets with absolute url
  • Start both servers.

Note: Make sure to have different ports to run both the servers.

var proxy = require('proxy-middleware');
var express = require('express');
var url = require('url');

//----------------- Web Proxy--------------------
var app = express();
app.use('/assets', proxy(url.parse('http://localhost:8000/dist/assets')));
app.get('/api/url', function(req, res) {}
app.post('/api/url', function(req, res) {}

// ---------------Webpack-dev-server---------------------
var server = new WebpackDevServer(webpack(config), config.devServer);

// ---------------Run both servers-----------------------
server.listen(config.port, 'localhost', function(err) {});
app.listen(8080);
like image 93
axiomtheorem Avatar answered Jan 03 '23 17:01

axiomtheorem