jantimon/html-webpack-plugin

Possibility to pass "locals" to the template

alesmenzel opened this issue · 1 comments

Is your feature request related to a problem? Please describe.
Problem: It is currently not possible to pass arbitrary values based on request into the template. One such usecase can be to preload some data, e.g. https://myapp.com?entityId=5 or https://myapp.com/detail/5 so we could fetch the data on the backend and save it into the template, so the app doesn't have to do another request when it is loaded.

Describe the solution you'd like
Adding some option to handle the request

// pseudo code
new HtmlWebpackPlugin({
  onRequest: (req, res, next, htmlWebpackPlugin) => {
    fetchEntity(req.query.enitityId, (err, entity) => {
      if (err) {
        next(err)
        return
      }
      
      // some kind of way to append data
      htmlWebpackPlugin.appendToBody(`<script>window.PRELOAD = ${escape(JSON.stringify(entity))}</script>`)
      
      // or more express way, where the locals would be available to use in the HTML template under some syntax, e.g. there is already the lodash syntax `<%= locals.entity %>` which would be the same if we use .ejs -> `<%= locals.entity %>`
      res.locals = {
        entity
      }
      
      next()
    })
  }
})

Describe alternatives you've considered
None - couldn't find a way to access the Request object.

Additional context
Maybe it is already possible, but I haven't found a good way.

Sorry out of scope this plugin, you can use hooks and implement a plugin for that, thank you