Skip to content

Instantly share code, notes, and snippets.

@elado
Last active October 6, 2016 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elado/f3bee45506c2b37be06e7c8bfcfbac68 to your computer and use it in GitHub Desktop.
Save elado/f3bee45506c2b37be06e7c8bfcfbac68 to your computer and use it in GitHub Desktop.
Webpack + Asset File Name + Server Rendering

Webpack + Asset File Name + Server Rendering

webpack.config.js

import AssetsPlugin from 'assets-webpack-plugin'

// ...

export default {
  // ...
  plugins: [
    // ...
    new AssetsPlugin({ filename: 'dist/assets.json' })
  ],
  // ...
}

server.js

let jsPath
if (process.env.NODE_ENV === 'development') {
  // WEBPACK_SERVER_URL env var points to the webpack-dev-server url (e.g. localhost:9000)
  // this express server runs on a different port in development (e.g. 9001)
  jsPath = `${process.env.WEBPACK_SERVER_URL}/dist/bundle.js`
}
else {
  jsPath = require('../dist/assets.json').main.js
}


// ...

app.get('/*', (req, res, next) => {
  // ...
  
  const reactOutput = ReactDOMServer.renderToString(/*...*/)

  res.render(path.resolve(__dirname, '..', 'views', 'index.ejs'), {
    // all variables like initialState
    jsPath,
    reactOutput
  })
})

app.listen(PORT, /* ... */)

views/index.ejs

<script src="<%= jsPath %>"></script>

<!-- ...  -->

<div id="app"><%- reactOutput %></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment