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

以上。

相关推荐
北海-cherish12 小时前
vue中的 watchEffect、watchAsyncEffect、watchPostEffect的区别
前端·javascript·vue.js
AALoveTouch12 小时前
网球馆自动预约系统的反调试
javascript·网络
2501_9159090613 小时前
HTML5 与 HTTPS,页面能力、必要性、常见问题与实战排查
前端·ios·小程序·https·uni-app·iphone·html5
white-persist14 小时前
Python实例方法与Python类的构造方法全解析
开发语言·前端·python·原型模式
新中地GIS开发老师14 小时前
Cesium 军事标绘入门:用 Cesium-Plot-JS 快速实现标绘功能
前端·javascript·arcgis·cesium·gis开发·地理信息科学
Superxpang14 小时前
前端性能优化
前端·javascript·vue.js·性能优化
左手吻左脸。14 小时前
解决el-select因为弹出层层级问题,不展示下拉选
javascript·vue.js·elementui
左手吻左脸。14 小时前
Element UI表格中根据数值动态设置字体颜色
vue.js·ui·elementui
李白的故乡14 小时前
el-tree-select名字
javascript·vue.js·ecmascript
Rysxt_15 小时前
Element Plus 入门教程:从零开始构建 Vue 3 界面
前端·javascript·vue.js