如何从Angular构建中添加或删除文件代码,不是取决于环境而是取决于目标?

问题描述 投票:0回答:1

我需要为我的Angular应用添加IE 10+支持。我已经成功地完成了几乎所有的工作--我已经启用了正确的polyfills,创建了额外的开发构建配置与es5目标来测试等等。我的应用程序在IE上成功运行,但有一个例外。我有一个nosleep.js库,它是避免移动设备屏幕锁定所需要的。如果这个库被附加到项目中,IE就无法解析它的代码,所以即使是像动态require这样的脏东西也无法运行。

@Injectable({
  providedIn: "root"
})
export class NoSleepService {
  noSleepEnabled = false;

  constructor() {
  }

  enable() {
    if(!this.noSleepEnabled) {
      const noSleep = require('nosleep.js');

      const noSleepObject = new noSleep();

      this.noSleepEnabled = true;
      noSleepObject.noSleepVideo.muted = true;
      noSleepObject.enable();

      console.log("Enabled nosleep", noSleepObject);
    }
  }
}

也许对于这个特殊的库,有其他的变通方法。但我不确定以后在其他需要的库上不会遇到同样的问题,所以我希望有一些通用的解决方案.也就是说,如果目标是es5,我希望在构建中排除库代码。所以,我不能把这个放到环境变量中,因为我的devprod环境有es6和es5两个目标。有没有办法根据在angular.json中配置的targetbuild来改变包含的文件代码?

angular typescript webpack polyfills
1个回答
1
投票

我有50%的把握这样做是行不通的:),但是你有没有尝试过 try catch?

enable() {
  if(!this.noSleepEnabled) {
    try {
      const noSleep = require('nosleep.js');
      // ..
    } catch {
      // apparently this is IE
    }
  }
}

如果不行的话,你也可以用load the 脚本 从你 index.html:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9">
<!--[if !IE]>-->
<script src="NoSleep.min.js"></script>
<!--<![endif]-->

终极和最好的解决办法是全部放弃对IE的支持,并作为一个强大的阵线团结起来,反对任何有这种可怕要求的人!。

© www.soinside.com 2019 - 2024. All rights reserved.