How to configure browser targetting with differential loading with es2016 or higher in angular 10

Viewed 2213

I am looking for some advice regarding JS target output for compiled angular when using differential loading.

It seems that out of the box the typescript in angular is compiled down to es5 and es2015 and depending on browser capabilities either the browser uses es5 or es2015.

To keep things up-to-date I have been studying the different ES versions and the browsers that support them.

But I have hit a brick wall and I can't seem to get any more information about this topic.

I decided to increase the target output from es2015 to es2016 as it seems most modern browsers have full support for ES2016.

I did this by setting the target value in tsconfig.json

"compilerOptions": {
    "target": "es2016"
}

However, I have hit a snag.

I'm getting the following warning on compile

Warning: Using differential loading with targets ES5 and ES2016 or higher may cause problems. Browsers with support for ES2015 will load the ES2016+ scripts referenced with script[type="module"] but they may not support ES2016+ syntax.

So, basically I would like to understand how either Typescript/angular/the browser knows which is the right file to download when using a specific browser. (how does the targetting work)

Can this be configured on a per browser instance? IE;- these browsers are to use es5, these es2015 and these are to use es2016. I just don't understand how differential loading targets specific browsers.

And if there is any real benefit in using a later version than es2015 (I'm guessing fewer polyfills and more native code in the output? Faster? Smaller compiled files?

thanks in advance.

1 Answers

If you do an Angular build with differential loading ON, you'll notice that in index.html it has two sets of script tags for each module.

The targeting is specified like this:

<script src="runtime-es2015.js" type="module"></script>
<script src="runtime-es5.js" nomodule></script>

And you'll notice two difference, nomodule and type="module". nomodule tells latest browsers that this is es5 and can be ignored. So latest browsers won't load this script, but older browsers will load this and execute. Check nomodules attribute in mdn.

Also, Angular document says that it doesn't support differential loading for target other than es2015 and would throw the warning that you have mentioned.

You can configure the supported browser versions using .browserslistrc. Check this & this.

By using es2015 you should already be getting smaller bundles (While older browsers will continue to load larger es5 bundles). If users have modern browsers but older version, then there is a possibility that they might have runtime error if target is not es2015, say you use Array.flat which is supported from chrome 69 but user has chrome 68 or something.

Related