Express Integration

Now that I can make a working webpack build, I will add a server to serve my html and assets.
To use express we will need two new packages | express & webpack-dev-middleware.

  • Add express and the middleware to the project
    • yarn add express webpack-dev-middleware
  • Add publicPath: '/' to the output object in webpack.config.js.

webpack.config.js

...output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist'),
/*+*/ publicPath: '/'
 }
  • Make a new file named server.js in the root dir.
    • touch server.js

server.js

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

 const express = require('express')
 const app = express()

 /*
 ** Tell express to call webpack
 ** and serve the compiled assets
 */
 app.use(webpackDevMiddleware(compiler, {
        publicPath: config.output.publicPath
 })

 /*
 ** Serve the index.html file
 */
 app.get('/', (req, res) => {
        res.sendFile(path.resolve(__dirname, 'dist/index.html'))
 })

       // Listen on port 3000        
        app.listen(3000, () => {
               console.log('Server running @ http://localhost:3000')
        })
  1. Last add a new run script to package.json

package.json

    //...
"scripts": {
   "build": "webpack",
   "start": "node server.js"
 }// rest of package.json
This is great but it be even better if the app could update on file saves instead of having to reload the page, so next I add webpack-dev-middleware.

results matching ""

    No results matching ""