7
votes

I have an existing express server that serves up the static assets/api data calls. How does one typically integrate webpack into this sort of setup? Does one have to run the webpack dev server to have hot module replacement? Is there any way to have webpack bundle all the modules and then just do hot module replacement by requesting static assets from an already existing server?

Thanks in advance.

1

1 Answers

7
votes

Here is my minimal express setup that does HMR

server.js

 
var express = require('express')
var app = express()

var morgan = require('morgan')

var env = app.get('env')

if (env == 'development') {
  var webpack = require('webpack')
  var webpackDevMiddleware = require('webpack-dev-middleware')
  var webpackHotMiddleware = require('webpack-hot-middleware')

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

  app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }))
  app.use(webpackHotMiddleware(compiler))
  app.use(morgan('dev'))

  app.get("/", function(req, res) {
    res.sendFile(__dirname + '/index.html')
  })
}

app.listen(8080, function(error) {
  if (error) {
    console.error(error)
  } else {
    console.info("==> 🌎  Listening on port %s. Open up http://localhost:%s/ in your browser.", 8080, 8080)
  }
})

and webpack.config.js (I removed some clutter, to leave it pretty minimal)

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

module.exports = {
  entry: [
    'webpack-hot-middleware/client',
    './index',
  ],
  output: { 
    path: __dirname, 
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
    loaders: [
      {test: /.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: {presets: ['es2015', 'react']} },
    ]
  },
};

I think this should give you enough information to incorporate webpack into your express server.