Skip to main content

Command Palette

Search for a command to run...

Use webpack-dev-middleware along with html-webpack-plugin in dev mode, HMR enabled

Published
2 min read
Use webpack-dev-middleware along with html-webpack-plugin in dev mode, HMR enabled

webapck

Webpack-dev-server is sweet, but when you have some routes in your back end and have to handle them with other logic instead just redirect them to your spa, webpack-dev-middleware may be one of your options.

We can use webpack-dev-middleware along with express, but here is one problem. Except routes mentioned above, you still need to respond remaining requests with your index page, especially when html-webpack-plugin is involved, because when we enabled HMR, the compiled index page only exists in memory, we don’t know it’s precise location.

So here is the solution: HtmlWebpackPlugin + webpack-dev-middleware other pathname than / · Issue #145 ·… Hello, First, thank you for your wonderful work! Second ,) My issue, I tried to use HtmlWebpackPlugin with dev server…github.com

var express = require('express');
var app = express();
var webpack = require('webpack');
var path = require('path');

var compiler = webpack(require('./webpack.config.js'));

var devMiddleware = require('webpack-dev-middleware');

app.use(devMiddleware(compiler, {
  noInfo: true,
  publicPath: '/'
}));

app.use('*', function (req, res, next) {
  var filename = path.join(compiler.outputPath,'index.html');
  devMiddleware.waitUntilValid(() => {
    compiler.outputFileSystem.readFile(filename, function(err, result){
      if (err) {
        return next(err);
      }
      res.set('content-type','text/html');
      res.send(result);
      res.end();
    });
  });
});

app.listen(3000);
132 views

More from this blog

Al's blog

21 posts