vue项目index.html中使用环境变量的代码示例

 更新时间:2024年02月26日 08:25:51   作者:下雪天的夏风  
在Vue3中使用环境变量的方式与Vue2基本相同,下面这篇文章主要给大家介绍了关于vue项目index.html中使用环境变量的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下

1,Vue-CLI(Webpack)

<!DOCTYPE html>
<html lang="">
  <head>
    <link rel="icon" href="<%= BASE_URL %>favicon.ico" rel="external nofollow"  />
    <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>
  • 在 vue-cli 创建的项目中,index.html 使用环境变量时通过 <%= xxx %>参考

  • 除了 VUE_APP_* 变量之外,始终可使用的变量有2个 NODE_ENV 和 BASE_URL参考

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

2,Vite

<!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>

编译结果

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

以上。

总结

到此这篇关于vue项目index.html中使用环境变量的文章就介绍到这了,更多相关vue index.html使用环境变量内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论