You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中禁止脚本在localhost运行,仅在生产环境执行?

让index.html中的脚本仅在生产环境执行(禁止localhost运行)

这里提供两种实用方案来实现需求:

方案1:直接通过域名判断(快速实现)

在脚本中添加本地域名的判断逻辑,仅当当前环境不是localhost/127.0.0.1等本地地址时,才执行核心代码:

<!doctype html>
<html lang="pl">
<head>
  <meta charset="utf-8">
  <title>Angular Homework Task</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Start script -->
  <script type="text/javascript">
    // 匹配常见本地主机名,排除后判定为生产环境
    const isProduction = !window.location.hostname.match(/localhost|127\.0\.0\.1|::1/);
    
    if (isProduction) {
      (function(w,d,s,a,b) {
        a=d.createElement(s),a.innerHTML="alert('Attention production!')",b=d.getElementsByTagName(s)[0],b.parentNode.insertBefore(a,b);
      })(window,document,'script');
    }
  </script>
  <!-- End script-->
</head>
<body>
  <app-root></app-root>
</body>
</html>

这种方案无需依赖项目配置,直接在客户端完成判断,适合快速验证需求。

方案2:利用Angular环境变量(规范项目做法)

Angular原生支持环境区分配置,通过构建时的变量替换,彻底在生产包中保留脚本、开发包中移除脚本:

  1. 确保项目src/environments目录下有两个配置文件:

    • environment.ts(开发环境):export const environment = { production: false };
    • environment.prod.ts(生产环境):export const environment = { production: true };
  2. 修改index.html,用模板语法控制脚本加载:

<!doctype html>
<html lang="pl">
<head>
  <meta charset="utf-8">
  <title>Angular Homework Task</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- 仅在生产环境加载脚本 -->
  <% if (environment.production) { %>
  <script type="text/javascript">
    (function(w,d,s,a,b) {
      a=d.createElement(s),a.innerHTML="alert('Attention production!')",b=d.getElementsByTagName(s)[0],b.parentNode.insertBefore(a,b);
    })(window,document,'script');
  </script>
  <% } %>
</head>
<body>
  <app-root></app-root>
</body>
</html>

构建时Angular会自动根据环境变量替换模板内容,开发环境下脚本块会被完全移除,生产环境则保留,更符合项目规范且安全。

内容的提问来源于stack exchange,提问作者LasagneLover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 21:11:38