vue 项目 index.html 中使用环境变量

目录

1,Vue-CLI(Webpack)

html 复制代码
<!DOCTYPE html>
<html lang="">
  <head>
    <link rel="icon" href="<%= BASE_URL %>favicon.ico" />
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <div id="app"></div>
    <script>
      console.log('<%= NODE_ENV %>')
      console.log('<%= BASE_URL %>')
      console.log('<%= VUE_APP_CONTEXT %>')
    </script>
  </body>
</html>
  1. 在 vue-cli 创建的项目中,index.html 使用环境变量时通过 <%= xxx %>参考

  2. 除了 VUE_APP_* 变量之外,始终可使用的变量有2个 NODE_ENVBASE_URL参考

  3. vue-cli 内置了 htmlWebpackPlugin 插件,其中 htmlWebpackPlugin.options.title 默认取的是 package.json 中的 name 字段。

2,Vite

html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>%MODE%</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
    <script>
      console.log('%MODE%')
    </script>
    <script type="module">
      console.log(import.meta.env.MODE)
    </script>
  </body>
</html>

编译结果

html 复制代码
<script>console.log('development')</script>
<script type="module" src="/index.html?html-proxy&amp;index=0.js"></script>
  1. vite 创建的项目中,index.html 使用环境变量有2种方式:
  • 通过 %xxx%参考
  • <script type="module"> 中通过 es6 的模块语法,使用 Vite 创建的 import.meta.env 对象上暴露的环境变量。
  1. 始终可使用的变量有4个。参考

以上。

相关推荐
kyriewen113 小时前
你点的“刷新”是假刷新?前端路由的瞒天过海术
开发语言·前端·javascript·ecmascript·html5
摇滚侠4 小时前
JAVA 项目教程《苍穹外卖-12》,微信小程序项目,前后端分离,从开发到部署
java·开发语言·vue.js·node.js
Timer@4 小时前
LangChain 教程 04|Agent 详解:让 AI 学会“自己干活“
javascript·人工智能·langchain
阿珊和她的猫5 小时前
TypeScript中的never类型: 深入理解never类型的使用场景和特点
javascript·typescript·状态模式
skywalk81635 小时前
Kotti Next的tinyfrontend前端模仿Kotti 首页布局还是不太好看,感觉比Kotti差一点
前端
RopenYuan7 小时前
FastAPI -API Router的应用
前端·网络·python
走粥7 小时前
clsx和twMerge解决CSS类名冲突问题
前端·css
Purgatory0017 小时前
layui select重新渲染
前端·layui
weixin199701080168 小时前
《中国供应商商品详情页前端性能优化实战》
前端·性能优化