[Vuejs]-How to enable dotenv variables for a file inside the /public folder in a Vue project?

1👍

Use this standard plugin to generate navbar.html. https://github.com/jantimon/html-webpack-plugin.

If you read the docs, the templateParameters option is what you pass env variables to. Those variables will be available in navbar.html.

This is the same plugin that vue-cli uses for index.html. If you run the vue inspect command, you can see what options they provide to the plugin. You’ll need to read the source code for resolveClientEnv() to see how it works.

Example:

    /* config.plugin('html-portal') */
    new HtmlWebpackPlugin(
      {
        templateParameters: (compilation, assets, pluginOptions) => {
                // enhance html-webpack-plugin's built in template params
                let stats
                return Object.assign({
                  // make stats lazy as it is expensive
                  get webpack () {
                    return stats || (stats = compilation.getStats().toJson())
                  },
                  compilation: compilation,
                  webpackConfig: compilation.options,
                  htmlWebpackPlugin: {
                    files: assets,
                    options: pluginOptions
                  }
                }, resolveClientEnv(options, true /* raw */))
              },
        minify: {
          removeComments: true,
          collapseWhitespace: true,
          removeAttributeQuotes: true,
          collapseBooleanAttributes: true,
          removeScriptTypeAttributes: true
        },
        chunks: [
          'chunk-vendors',
          'chunk-common',
          'portal'
        ],
        template: 'C:\\Users\\Eric\\workspace\\arc-core\\portal\\client\\templates\\portal.html',
        filename: 'portal.html',
        title: 'Arc Portal'
      }
    ),

That’s a bit much, a minimal example would be:

new HtmlWebpackPlugin({
    // This is the generated file from the build, which ends up in public/navbar.html
    filename: 'navbar.html',
    // This is the source file you edit.
    template: 'templates/navbar.html',
    templateParameters: {
        MY_VAR: 'myVar'
    }
}),

Leave a comment