String replacements in index.html in vite

Viewed 4704

I am trying to inject some strings into the index.html of a Vite app (using vue3 template). In a vue-cli project for example we would have

<link rel="icon" href="<%= BASE_URL %>favicon.ico">

What is the Vite way to do that? (I know that BASE_URL is just '/' in this case. I am asking for the general solution) I would be fine with a solution that covers environment variables only, but it would be great to know an even more general solution that can use JS code as in

<title><%= htmlWebpackPlugin.options.title %></title>

And I would really appreciate a solution that doesn't require installing an npm package

1 Answers

Had to lower my expectations considerably:

  1. I install a package
  2. I "cheat" and use process.env
// vite.config.js
import vue from '@vitejs/plugin-vue'

import { loadEnv } from 'vite'
import { createHtmlPlugin } from 'vite-plugin-html'

export default ({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  return {
    plugins: [
      vue(),
      createHtmlPlugin({
        minify: true,
        inject: {
          data: {
            title: env.VITE_MY_FOO,
          }
        }
      }),
    ],
  }
}

then in .env

VITE_MY_FOO="Hello vite ejs"

and in index.html

<title><%= title %></title>

Can't say I like it, but it works

Related