1252748
1252748

Reputation: 15362

How to use webpack to deploy an Express + React app

I have a project which for development uses webpack-dev-server. I would like to deploy the app using an express server that would serve its content via Pug templates, or just the static HTML page produced by HtmlWebpackPlugin when running production webpack. Current setup:

 ──┬ 📁  dist
 | └──┬ 📁  server
 | |  └──┬ 📁  views // moved by CopyWebpackPlugin
 | |  |  ├─── 📄  error.pug
 | |  |  └─── 📄  index.pug
 | |  ├─── 📄  index.js // bundled server
 | ├─── 📄  bundle.js   // bundled front-end
 | ├─── 📄  index.html  // produced by HtmlWebpackPlugin
 └───── 📄  root.710...2.css
...

 ───┬ 📁  src
 |  └──┬ 📁  js
 |  |  ├─── 📄  app.jsx 
 |  └──┬ 📁  server
 |  |  └──┬ 📁  routes
 |  |  |  ├─── 📄  index.js  // route that might? serve index.pug
 |  |  |  ├─── 📄  routes.js // routes to other endpoints hit by front end code
 |  |  └──┬ 📁  views
 |  |  |  ├─── 📄  error.pug
 |  |  |  └─── 📄  index.pug // HtmlWebpackPlugin given this as template path
 |  |  ├─── 📄  app.js // express server
 |  └──┬ 📁  styles
 └─────└─── 📄  main.scss

Webpack bundles both my server and my front end components into dist/server/index.js and dist/bundle.js. The server provides a few routes that the front end XHR's to access some data. I'm struggling with how what the canonical way to deploy this code would be so that I can use the templated pages to display some variable information from the paths (eg, error.pug getting some data like {code: 404}) but also the hashes generated by HtmlWebpackPlugin that give urls like those produced by filename: '[name].[hash].bundle.js'.

Should the express server not to attempt to serve the index based upon environment?

if (process.env.NODE_ENV === 'production') {
  router.get('/', (req, res) => {
    res.render('index')
  })
}

If so, how should the pug template look like to consume the [name].[hash].bundle.js? Should the pug file be used only for the error page? Should it be a different Express server entirely that serves the index/error pages from a server that serves the API data consumed by the front end?

What is the canonical best practice to produce for production an express server to serve a bundled react app?

Upvotes: 1

Views: 302

Answers (1)

Francois
Francois

Reputation: 3080

Better is to have a dist this way

/dist
  /client
    root.710...2.css
    bundle.js
    index.html
  /server
    /views
      error.pug
      index.pug
    index.js

Then have your express server (or nginx) serve the client folder. app.use(express.static('/path/to/your/dist/client'));

Upvotes: 2

Related Questions