ES6 Code in an Angular Project

Written by Preston Lamb

Posted on Aug 15, 2018


I was recently working on an Angular project where I was loading a JavaScript file into the application in the .angular-cli.json file (the same would happen if your file is the angular.json file). The file was pretty simple, only about 40 lines at most. But it was using ES6 syntax (like const) and a for(const - of -) loop. I've been writing JavaScript like that for a long time, in my Node.js applications and in TypeScript in Angular projects. It's just second nature now, and I didn't think anything of it.

The issue came a few days ago when I attempted to do a production build when we were going to deploy the application. I ran the ng build --prod command, and about halfway through I got an error:

Sometimes I'd get this error, and sometimes it was different but similar. The error was something about "unexpected token const". It wasn't real specific though, and I had no idea what file to even look in to figure out what the issue was. So I just started googling the issue, and was lucky enough to come across this GitHub issue that pointed me in the right direction. Specifically, I found this comment:

At that point I was able to go back into my codebase and figure out what the issue was. Because the file was small enough, I was able to manually change it back to ES5 syntax. After doing that, the build succeeded and I could move on.

This issue may not come up that often, because you may not write ES6 code that you include through the .angular-cli.json file like I did. But if you need to, don't forget to either write valid ES5 to begin with, or run the code through Babel or another JavaScript compiler and include that file in the project.