Syntax Error in Angular App: Unexpected token <
Got this error as well using angular with express.
I guess when you build an angular project the project is stored in 'dist/the-app' not just 'dist' so this solved my problem on express.
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist/the-app')));
for me, this error was due to not setting the proper path of the built application.
The problem is with the <base href="/">
part of index.html
file, it seems angular generates build file inside dist/{yourProjectName}/
but the index.html
files goes through the dist/
for build files. Now you have 2 options:
Change the
<base href="/">
part of theindex.html
file to<base href="/dist/{yourProjectName}/">
but now you have inconsistency between theng serve
command andng build
and you can't see your project throughng serve
. So you have change that part every time!The seccond approach that I recommend, is just changing the output path of the project! Go to your
angular.json
file of your project and change the"outputPath": "dist/{yourProjcetName}",
to"outputPath": "dist/"
and don't change thebase href
!
I had the same issue:
1) I ran the command
ng build --aot --prod
2) Everything compiled without an error
3) I deleted all the files on the server and copied it all across via FTP(FileZilla) to a windows Azure server
4) Sometimes I get the error
Unexpected token <
and other-times not
Yesterday I noticed that the main[hash].js was missing on the server and that Filezilla did not give me an error copying it.
I then tried copying only that file.It did not work. When I removed the hash part from the filename it copies without a problem.
Work-a-round
Run:
ng build --aot --prod --output-hashing none
Which works every-time.
So either Filezilla or Windows Server does not allow filenames with a specific length or it does not like certain hashes.
This is most likely the result of a 404 page or a redirect to a page that serves regular html instead of the expected JavaScript files.
(A HTML page starts with <html>
or a <!DOCTYPE...>
)
Make sure that you have correctly uploaded the files and access the page correctly. You can verify by manually accessing the URL with the browser or look into the network tab of your browser development tools to inspect the response.