vue.jsbuildenvironment-variablesvue-cli-4

How to add HTML comments to index.html when doing a build in Vue CLI?


Update 1: Fixed syntax issue that caused my initial build errors.

Update 2: Found my own solution using a Webpack plugin. See the accepted solution.

I want to add some custom HTML comments in the public/index.html during a build. I added something like this:

<!--
My Application
Version: <%= VUE_APP_VERSION %>
Build date: <%= VUE_APP_BUILD_DATE %>
-->

In my vue.config.js, I've set VUE_APP_VERSION and VUE_APP_BUILD_DATE accordingly:

let today = new Date().toLocaleDateString(undefined, {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit'
})

process.env.VUE_APP_VERSION = require('./package.json').version
process.env.VUE_APP_BUILD_DATE = today

But when I actually build (npm run build), the comments are removed completely and everything is minimized.

How do I preserve my comments?


Solution

  • Found a solution using HtmlWebpackPlugin and WebpackAutoInject plugins in my vue.config.js file; ditching the VUE_APP_* variable use in my index.html as it was causing me build errors.

    npm install html-webpack-plugin --save-dev
    npm install webpack-auto-inject-version --save-dev
    

    My new vue.config.js:

    const HtmlWebpackPlugin = require('html-webpack-plugin')
    const WebpackAutoInject = require('webpack-auto-inject-version')
    
    module.exports = {
      publicPath: process.env.NODE_ENV === 'production'
        ? process.env.VUE_APP_PUBLIC_PATH_EN
        : '/',
    
      configureWebpack: {
        plugins: [
          // index.html customization
          new HtmlWebpackPlugin({
            template: 'public/index.html',
            filename: 'index.html',
            inject: true,
            deploy: process.env.VUE_APP_DEPLOY,
            webtrends: '/webtrends/scripts/webtrends.load.js', // include webtrends script for OPS only
            minify: {
              removeComments: false
            }
          }),
    
          // Auto inject version
          new WebpackAutoInject({
            SILENT: true,
            // options
            components: {
              AutoIncreaseVersion: false,
              InjectAsComment: false
            },
            componentsOptions: {
              InjectByTag: {
                // https://www.npmjs.com/package/dateformat
                dateFormat: 'isoUtcDateTime'
              }
            }
          })
        ]
      }
    }
    

    Then in my index.html (with a custom script to include on build):

    <!--
    My application
    Version: [AIV]{version}[/AIV]
    Build date: [AIV]{date}[/AIV]
    -->
    <% if (htmlWebpackPlugin.options.deploy === 'ops') { %>
        <script src="<%= htmlWebpackPlugin.options.webtrends %>"></script>
    <% } %>