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

以上。

相关推荐
ym hyd 1115 小时前
试题库管理系统源码 Java+SpringBoot+Vue3 前后分离
java·vue.js·spring boot·毕设
迅猛龙办公室5 小时前
Python输出当前计算机的系统日期和时间
开发语言·前端·python
小狼154546 小时前
浏览器扩展脚本为什么有时候不生效:注入时机、iframe 和单页路由,多多开票助手
前端·chrome
じòぴé南冸じょうげん6 小时前
油猴脚本突然发现变成灰色了,无法使用?页面不生效?刷新页面没反应?
前端
Csvn8 小时前
组合式 API(Composition API)
前端
火柴就是我9 小时前
Android 打包报错 25.0.3
android·前端
BD_Marathon9 小时前
消息对象中字段的说明
java·前端·python
八荒启·交互动画9 小时前
Web特效025—用 Canvas 2D 做Web特效的定义与边界:这支画笔能做到哪一步
前端·webgl·网页特效·八荒启-交互动画·八荒启
Ai-_Man9 小时前
您您这可以把Dola的多个会话比如说。左侧的多个会话一次性导出吗?不是单条会话里面的多次会对话。用AI导出鸭,答案是可以的
开发语言·前端·人工智能·小程序
excel9 小时前
Nuxt 中使用 useHead 优化 SEO 与 GEO
前端