题意:
在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:
不得不大大降低我的期望:
- I install a package 我安装了一个包。
- 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
不能说我喜欢它,但它确实有效。