Inserting Environment Variables into HTML files other than Index Using Vuejs

Viewed 604

I've been developing a project built using the Vue CLI v3.*

I'm aware of how environment variables can be inserted into the Index.html file. But what about other html files?

Now that I am including oidc and silent refresh capability, I need to include a few more html files into the Public folder for the callbacks from the Identity Server e.g. Silent-refresh.html.

That file includes the url of the Identity Server in some of the meta elements, to satisfy CSP measures.

At the moment, when I swap between hitting my local Identity Server and a deployed one, I have to copy and paste the url into all places in the app.

It would be nice if I could just set it as an environmental variable, prefrexed with VUE_APP for use across the project, including such html files. Then I only have to change it in one place.

Is there a way to do this? I believe some kind of webpack HTML plugin is involved, but I don't know how to configure it in such a way as to work with the Webpack plugin which is doing the same for the Index.html file.

The meta tags look like this:

    <meta
      http-equiv="Content-Security-Policy"
      content="frame-src <%= VUE_APP_IDPURL %>;"
    />

Thanks

1 Answers

You should use the pages property in the vue.config.js module.exports to include the configuration for a different page than index.html.

You would have to include the configuration for your index.html file and the alternate page(s) as follows:

module.exports = {
  pages: {
    index: {
      // entry for the page
      entry: 'src/index/main.js',
      // the source template
      template: 'public/index.html',
      // output as dist/index.html
      filename: 'index.html',
      // when using title option,
      // template title tag needs to be <title><%= htmlWebpackPlugin.options.title %></title>
      title: 'Index Page',
      // chunks to include on this page, by default includes
      // extracted common chunks and vendor chunks.
      chunks: ['chunk-vendors', 'chunk-common', 'index']
    },
    silentRefresh: {
      // you may use an empty noop js file because you only want to use the html template
      entry: 'src/index/silentRefresh.js',
      template: 'public/Silent-refresh.html',
      filename: 'Silent-refresh.html',
      title: 'Alternate Page'
    }
  }
}

Here's the reference to the docs on the pages property.

Related