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个。参考

以上。

相关推荐
掘金安东尼5 小时前
纯 CSS 实现弹性文字效果
前端·css
牛奶5 小时前
Vue 基础理论 & API 使用
前端·vue.js·面试
牛奶5 小时前
Vue 底层原理 & 新特性
前端·vue.js·面试
anOnion6 小时前
构建无障碍组件之Radio group pattern
前端·html·交互设计
pe7er6 小时前
状态提升:前端开发中的状态管理的设计思想
前端·vue.js·react.js
SoaringHeart7 小时前
Flutter调试组件:打印任意组件尺寸位置信息 NRenderBox
前端·flutter
晚风予星7 小时前
Ant Design Token Lens 迎来了全面升级!支持在 .tsx 或 .ts 文件中直接使用 Design Token
前端·react.js·visual studio code
sunny_7 小时前
⚡️ vite-plugin-oxc:从 Babel 到 Oxc,我为 Vite 写了一个高性能编译插件
前端·webpack·架构
GIS之路8 小时前
ArcPy 开发环境搭建
前端
林小帅9 小时前
【笔记】OpenClaw 架构浅析
前端·agent