Angular2 why do we need the es6-shim
Asked Answered
M

2

21

Following the Angular2 Quickstart Guide we are instructed to include es6-shim in 2 places:

1) index.html

<script src="node_modules/es6-shim/es6-shim.min.js"></script>

2) typings.json

"ambientDependencies": {
  "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#6697d6f7dadbf5773cb40ecda35a76027e0783b2"
}

I was under the impression that we are compiling our es6 code down to es5.

Configured in tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    ...

If the end result is that the browser is loading es5, why does the browser needs shims for es6?

Motherly answered 26/2, 2016 at 2:20 Comment(0)
E
30

Typings are used by your editor to give you code hinting/intellisense, and es6-shim.min.js is a code that emulates ES6 features for ES5 browsers. Some of those features are Promise, Array.from()...

While your code is translated to ES5, you need to include es6-shim so you can use those new features in it... Consider this ES6 code:

let test1 = () => 123 + 456;
let test2 = new Promise((resolve, reject ) => {});

it will be translated to ES5 code:

var test1 = function () { return 123 + 456; };
var test2 = new Promise(function (resolve, reject) { });

but without es6-shim Promise would be undefined...

Eclosion answered 26/2, 2016 at 2:35 Comment(2)
you mean hinting/intellisense given by editor is using es6-shim ?Cretaceous
And as of Oct 2016, they are now recommending core-js over es6-shim in their quick start referenced by the OP.Pyroclastic
E
13

TypeScript does not come with built-in polyfills. There are certain features it doesn't transpile, this is where polyfills like es-shim come in.

The TypeScript definition file will provide you with typing support within your chosen editor and the es-shim will provide the implementation for the functionality that TypeScript doesn't transpile to ES5 code.

A few of such features TypeScript doesn't transpile are:

  • Promises
  • Functions hanging off of prototype objects (Array.from(),Array.of(),Number.isInteger(), etc)
  • Module loading

The general approach is:

The rule of thumb is that if there's a canonical/sane emit that doesn't have a huge perf-hit, we'll try to support it. We don't add any runtime methods or data structures, which is more what core.js (or any pollyfil) serves to do. - source (TypeScript developer)

Elsy answered 26/2, 2016 at 2:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.