适用开发过程中在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' ) { %>
//这里写需要的代码
<% } %>

该博客介绍了如何在开发过程中,在HTML的index.html文件中实现根据不同环境(如生产环境)打包不同的代码。通过条件语句`<% if (process.env.NODE_ENV === 'production') {%>`,在生产环境中插入特定的JavaScript代码,例如设置全局变量`window.test`。这种方法有助于在部署时实现代码的差异化处理,确保生产环境的优化和安全。
1660





