Detuned
Detuned

Reputation: 3758

What's the purpose of having express use webpack dev server?

I'm trying to understand the reason why one would like the webpack server for applications where webpack is bundling and serving the client side code and express for the api.

For example. I'd imagine you would have express running on a port and webpack running on a different port and you would proxy all requests to webpack over to the back express backend.

However, I continue seeing this usage:

const app = express();  
const compiler = webpack(config);

app.use(express.static(__dirname + '/dist'));  
app.use(webpackMiddleware(compiler);  
app.use(webpackHotMiddleware(compiler)); // And this line  

What's the reason for having express use this server?

Upvotes: 1

Views: 415

Answers (1)

bren
bren

Reputation: 4334

Webpack does not work for the server, it's a way to write you include MDN modules into your browser. In your code, webpack is "latching on" to express, and will handle some of its requests. This is called middleware, and is the backbone of most server libraries in node.js (with the exception of Meteor). In this code there is only one (forward-facing) server, even though express likes to compartmentalize in a way that indicates otherwise. Let's run through the important lines in your code:

const app = express();  
const compiler = webpack(config);

app.use(express.static(__dirname + '/dist'));  

The line above looks in /dist and sees if there's a file to give the browser. As per normal, this middleware is usually before any dynamic pages are processed.

app.use(webpackMiddleware(compiler);  
app.use(webpackHotMiddleware(compiler)); // And this line  

If the static server couldn't handle this request, then give them the webpack template

Hope this was helpful,
Brendan McGuire

Upvotes: 2

Related Questions