String replacements in index.html in vite

题意

在Vite的index.html中进行字符串替换

问题背景:

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

我正在尝试将一些字符串注入到Vite应用的index.html中(使用Vue 3模板)。例如,在vue-cli项目中,我们会有

<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

Vite中实现这个的方式是什么?(我知道在这种情况下BASE_URL只是'/'。我是在询问通用的解决方案)我可以接受仅涉及环境变量的解决方案,但如果能知道一个更通用的解决方案,能够像下面这样使用JS代码,那就太好了。

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

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

我非常感谢一个不需要安装npm包的解决方案。

问题解决:

Had to lower my expectations considerably:

不得不大大降低我的期望:

  1. I install a package   我安装了一个包。
  2. I "cheat" and use process.env   我“作弊”并使用 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

不能说我喜欢它,但它确实有效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

营赢盈英

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值