如何在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原生支持环境区分配置,通过构建时的变量替换,彻底在生产包中保留脚本、开发包中移除脚本:
确保项目
src/environments目录下有两个配置文件:environment.ts(开发环境):export const environment = { production: false };environment.prod.ts(生产环境):export const environment = { production: true };
修改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
相关产品推荐
相关产品推荐

