vue-cli的index.html中使用环境变量方式

2022-10-21 11:00:42

目录vue-cli的index.html使用环境变量vue-cli在index.html判断环境变量加载不同代码vue-cli的index.html使用环境变量项目中使用了公司定义的统一头部文件,需要...

目录
vue-cli的index.html使用环境变量
vue-cli在index.html判断环境变量加载不同代码

vue-cli的index.html使用环境变量

项目中使用了公司定义的统一头部文件,需要引入header.js和header.css。负责人希望各个环境引入各自的js和css。

当时第一反应是process,但是在index.html里打印报错,所以最初是根据域名去判断,然后动态修改src和href值。感觉很麻烦。

翻阅cli官方文档后看到了这样一段话。

vue-cli的index.html中使用环境变量方式

遂使用了一下,发现是可以的,具体写法如下:

.env.xxx环境文件中定义变量:

VUE_APP_APIURL = "http://test.xxxx.com.cn"

然后html文件中使用

<link rel="stylesheet" href="<%= VUE_APP_APIURL %>/header/head.css" rel="external nofollow" >

vue-cli在index.html判断环境变量加载不同代码

适用开发过程中在index.html页面根据不同环境打包不同代码的差异化场景,下面举例在打包生产环境时www.cppcns.com的差异处理:

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <meta name="keywords" content="" />
    <meta name="description" content="" />
    <link rel="icon" href="<%= BASE_URL %>favicon.ico" />
    <title><%= htmlWebpackPlugin.options.title %></title>
    <% if (process.env.NODE_ENV === 'production' ) { %>
    <script>
      window.test = "xxxx";
    </script>
    <% } %>
   
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

核心代码

<% if (process.env.NODE_ENV === 'production' ) { %>
  //这里写需要的代码
<% } %>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。