Module Parse Failed With Optional-Chaining in Angular 10 and ES2020
Asked Answered
E

1

6

Just updated to Angular 10 from 9.0

Every use of Optional Chaining (https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining) in my code now results in its own instance of the following error

ERROR in ./src/app/app.component.ts 39:18
Module parse failed: Unexpected token (39:18)
File was processed with these loaders:
 * ./node_modules/@ngtools/webpack/src/index.js
You may need an additional loader to handle the result of these loaders.
|         this.title = 'my-app';
|         const x = this.GetObject();
>         let y = x?.myvar;
|     }

I confirm that this error ONLY occurs when targeting es2020 as per below from my tsconfig.base.json file, but is fine when targeting es2019

"target": "es2020",  //If set to es2019 then all OK
"module": "es2020",
"lib": [
   "es2018",  //Error also occurs if this set to es2020
    "dom"
  ],

I confirm this error occurs in fresh Angular 10 application when newly generated as below, and then change target to es2020 (so it is not my code!) Typescript version is 3.9.7

npm install -g @angular/cli
ng new my-app

I also note that in the release notes of es2020 that 'Optional Chaining' is now a new feature. This makes me suspicious that Typescript compilation of 'Optional Chaining' somehow is not marrying up with the new es2020 feature?

How do I use Optional-Chaining in es2020?

Entirety answered 24/7, 2020 at 0:44 Comment(4)
This happens because TypeScript is behaving correctly, since option chaining is native in ES2020, it is not transformed by the compiler. @ngtools/wepack is subsequently parsing the code and doesn't understand the operator. Make sure that you don't have multiple versions of TypeScript installed by running npm ls typescriptLanford
Thanks Aluan, Should I raise this issue with the TypeScript dev team? If so, do you know where I would do so?Entirety
No, what I'm trying to explain is that it's not a TypeScript issue. It's another tool, apparently @ngtools/webpack, that doesn't understand the new syntax. setting target to ES2020, means ?. will not be transformed because it's part ECMAScript 2020. If you lower Target, then it transforms syntax that isn't native to that format, rewriting it into another syntactic form that isLanford
So then the question is, how do you use Angular with ES2020 with optional chaining, particularly when you need other 2020 features? Is there any way to tell Typescript to rewrite optional chaining while retaining the other features you need?Rase
E
3

Using Optional-Chaining in Angular 10 while targeting es2020 will result in the error 'Module parse failed: Unexpected token'

Current Workaround is to target es2019

Entirety answered 27/7, 2020 at 4:20 Comment(1)
What if you need features from 2020?Rase

© 2022 - 2024 — McMap. All rights reserved.