如何将自定义 polyfill 添加到 angular-cli 项目?

How to add a custom polyfill to an angular-cli project?

我需要能够轻松地对集合进行排序,因此我选择了扩展 Array 原语。我意识到在大多数情况下这被认为是不好的做法,但这只会在内部使用(不是共享库)。无论我尝试了哪种方法,即使它按预期工作,我也没有得到有效的结果 in the playground

我尝试在 /src/polyfills.ts 中添加 polyfill 内联,但这给了我一个“TypeError: Attempted to assign to readonly 属性”当我调用 $sortBy 方法时控制台...

declare global {
  interface Array<T> {
    $sortBy(sortKey:string): T[];
  }
}

if (!Array.prototype['$sortBy']) {

  Object.defineProperty(Array.prototype, '$sortBy', {
    value: function(sortKey) {
      return this.sort( function(a, b) { // TypeError here???
        if (a[sortKey] < b[sortKey]) { return -1; }
        if (a[sortKey] > b[sortKey]) { return 1; }
        return 0;
      });
    }
  })

}

我也尝试通过 npm 添加一个普通的 javascript 版本并导入,但这给了我相同的类型错误。有什么秘诀???

/node_modules/my-polyfills/sortBy.js

if (!Array.prototype.$sortBy) {
  Object.defineProperties(Array.prototype, {
    '$sortBy': {
      value: function (sortKey) {
        return this.sort(function (a, b) {
          if (a[sortKey] < b[sortKey]) {
            return -1;
          }
          if (a[sortKey] > b[sortKey]) {
            return 1;
          }
          return 0;
        });
      }
    }
  });
}

.angular-cli.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": { ... },
  "apps": [
    {
      ...,
      "scripts": [
        "../node_modules/my-polyfills/sortBy.js",
        "../node_modules/moment/moment.js"
      ],
      ...
    }
  ],
  ...
}

我在 angular cli 1.0.0 上生成了一个应用程序。虽然我认为您的问题与版本无关,但我已将您的代码放在下面并将其附加到 src/polyfills.ts 它按预期工作:

declare global {
  interface Array<T> {
    $sortBy(sortKey:string): T[];
  }
}

if (!Array.prototype['$sortBy']) {

  Object.defineProperty(Array.prototype, '$sortBy', {
    value: function(sortKey) {
      return this.sort( function(a, b) { // TypeError here???
        if (a[sortKey] < b[sortKey]) { return -1; }
        if (a[sortKey] > b[sortKey]) { return 1; }
        return 0;
      });
    }
  })
}

在我添加的一个组件中:

var a = [1,2,3];
var b = a.$sortBy('');
console.log(b)

我没有在控制台中看到错误,数组 a 打印得很好。

我认为您遇到的问题是因为您在 src/polyfills.ts 中包含了上面的代码,并且在 /node_modules/my-polyfills/sortBy.js 中包含了相同的 polyfill 并且将其添加到 .angular-cli

scripts 部分

您应该添加其中一个,而不是同时添加。我推荐前者,但在它自己的文件中而不是附加到 polyfills.ts

当您尝试将不可写的 属性 分配给其他内容时,会发生此错误 TypeError: Attempted to assign to readonly property。通过使用 Object.defineProperty 你使 $sortBy 不可写。您定义了 Arrays.prototype.$sortBy 然后您尝试通过将其分配给新函数来修改 $sortBy,因此您会收到错误。