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

以上。

相关推荐
u***u6851 小时前
React环境
前端·react.js·前端框架
X***E4631 小时前
前端数据分析应用
前端·数据挖掘·数据分析
4***14901 小时前
React社区
前端·react.js·前端框架
LFly_ice1 小时前
学习React-24-路由传参
前端·学习·react.js
Lhuu(重开版2 小时前
CSS:动效布局动画
前端·css
Q***K552 小时前
前端构建工具
前端
laocooon5238578862 小时前
创建了一个带悬停效果的“我的个人主页“按钮
前端
2013编程爱好者3 小时前
Vue工程结构分析
前端·javascript·vue.js·typescript·前端框架
小满zs4 小时前
Next.js第十一章(渲染基础概念)
前端
不羁的fang少年5 小时前
前端常见问题(vue,css,html,js等)
前端·javascript·css