目录Vue-cli的index.html使用环境变量vue-cli在index.html判断环境变量加载不同代码vue-cli的index.html使用环境变量 项目中使用了公司定义
项目中使用了公司定义的统一头部文件,需要引入header.js和header.CSS。负责人希望各个环境引入各自的js和css。
当时第一反应是process,但是在index.html里打印报错,所以最初是根据域名去判断,然后动态修改src和href值。感觉很麻烦。
翻阅cli官方文档后看到了这样一段话。
遂使用了一下,发现是可以的,具体写法如下:
.env.xxx环境文件中定义变量:
然后html文件中使用
<link rel="stylesheet" href="<%= VUE_APP_APIURL %>/header/head.css" rel="external nofollow" >
适用开发过程中在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="<%= 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' ) { %>
//这里写需要的代码
<% } %>
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: vue-cli的index.html中使用环境变量方式
本文链接: https://www.lsjlt.com/news/169843.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0