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

时间:2017-03-31 19:49:09

标签: angular typescript angular-cli polyfills

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

我尝试在/src/polyfills.ts中添加内联填充内容,但是当我调用{{1}时,这会在控制台中给出一个“ TypeError:尝试分配给readonly属性”方法......

$sortBy

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

/node_modules/my-polyfills/sortBy.js

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;
      });
    }
  })

}

.angular-cli.json

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;
        });
      }
    }
  });
}

1 个答案:

答案 0 :(得分:3)

我在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 AND 中包含上述代码,您已在/node_modules/my-polyfills/sortBy.js中添加了相同的填充,并将其添加到{{ 1}} scripts

的部分

您应该添加或不添加两者。我推荐前者,但在其自己的文件中,而不是附加到.angular-cli

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