jantimon / html-webpack-plugin

Simplifies creation of HTML files to serve your webpack bundles
MIT License
10.71k stars 1.31k forks source link

Possibility to pass "locals" to the template #1778

Closed alesmenzel closed 8 months ago

alesmenzel commented 1 year ago

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.

alexander-akait commented 8 months ago

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