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="https://www.jb51.net/article/<%= VUE_APP_APIURL %>/header/head.css" rel="external nofollow" >

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

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

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="https://www.jb51.net/article/<%= 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' ) { %>
    //这里写需要的代码
<% } %>

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。