Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 use ES2017 (e.g. string.prototype.padStart)

I'm using angular 4 and working on a string pipe to pad string with zeros. But angular or vs-code drops errors that the prototype "padStart" does not exist.

  1. How to setup this support to my project and / or editor?

  2. How to add polyfill if e.g. padStart does not exist?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

like image 947
Dominik Avatar asked Oct 28 '17 12:10

Dominik


2 Answers

In tsconfig.json you need to update the lib to be es2017.

Target (--target)

Specify ECMAScript target version

Lib (--lib)

List of library files to be included in the compilation.

Changing the lib to es2017 pulls in the typings for VSCode, and for compilation you can use polyfills.

Example

{
  "compileOnSave": false,
  "compilerOptions": {

    // ...

    "target": "es2015",

    // ...

    "lib": [
      "dom",
      "es2017" // <-- change to use es2017
    ],
    "paths": { ... }
  }
}

You can find the full list of compiler options in TypeScript's docs

Angular has a bunch of polyfills that are commented out by default in polyfills.ts. You can uncomment what you need and add the dependencies they request using npm or yarn. In your case you only need the string prototype polyfill from ES7.

like image 119
mtpultz Avatar answered Sep 30 '22 08:09

mtpultz


Add the following line in your polyfills.ts:

import 'core-js/es7/string';

padStart is part of es2017 (or es7 for short).

Or you can install the mdn-polyfills module and put this line:

import 'mdn-polyfills/String.prototype.padStart';

like image 39
AsGoodAsItGets Avatar answered Sep 30 '22 07:09

AsGoodAsItGets