'vue cli - Uncaught SyntaxError: Unexpected token <

I create my project with vue-cli 3.0. Initially it runs ok. But after I <ctrl>-c then npm run serve again, it keep throwing error:

Uncaught SyntaxError: Unexpected token <

it indicate that the error happened at the first line of app.js, but I check in console the < is actually from index.html. Which means somewhere along the process, the webpack thought index.html should be transpile as app.js.

Below are the packages I am using:

vue 3.0.0-rc.3 @vue/cli-plugin-babel ^3.0.0-beta.15 @vue/cli-plugin-eslint ^3.0.0-beta.15 @vue/cli-service ^3.0.0-beta.15

How can I resolve this?

Update01 I delete the whole node-modules folder and npm install again, then everything seems to work fine again. But if anyone have any idea why this happen, please share it.



Solution 1:[1]

Try by adding <base href="/" /> into the <head> of your index.html. Hope it will work.

Solution 2:[2]

You might have used "./" prefix for Relative path in src attributes of your index.html, Just replace it with "<%= BASE_URL %>" and it will work fine.

//<script src="./js/config.js">
<script src="<%= BASE_URL %>js/config.js">

This "./" usage won't cause any problems with normal Vue Routing but when you are implementing Dynamic Route Matching ({ path: '/user/:id', component: User }) your references in the index.html with "./" prefix won't work as expected!

This is because Vue file structure will place your dependencies inside your route folder like

user/js/config.js

This structure will be the same, Even when your route has route params (http://yourdomain.com/user/1234) since you have Dynamic Route Matching implemented and using the same Vue component (User.vue).

At this time, "./" might point for user/1234/js/config.js so it ends up going to a default 404 page and it's an HTML file that starts with "< html >", so you are getting "Uncaught SyntaxError: Unexpected token <" in line 1 of your referenced file.

Solution 3:[3]

I had the same problem, I tried the removing node modules and npm install again but that didn't work.

What did work was removing all the site data. You can do that (in Chrome) by opening the development tab (Ctrl+Shift+i), go to the 'application' tab, click "Clear storage" on the side panel and click on the "Clear site data" button.

My guess is that I still had some old service-worker that intercepted the request and served the html file instead of the app.js. So if you have used PWA's before at the url "http://localhost:8080" this might solve the problem.

Solution 4:[4]

// vue.config.js
module.exports = {
  publicPath: '/',
};

You actually want to add the publicPath to your vue.config.js file

https://stackoverflow.com/a/56320964/1321009 does work if you application is deployed at http://example.com

If you deployed it at http://example.com/something

Then you would need to go in and change it when deploying, annoying to say the least.

with vue.config.js file just set it like this

// vue.config.js
module.exports = {
  publicPath: process.env.NODE_ENV === 'production'
    ? '/something/'
    : '/'
};

Solution 5:[5]

I have the same problem. in index.html file , I just write this script tag,like this :

  <script src="./static/js/qrcode.min.js"></script>

if I change src attr like this:

 <script src="/static/js/qrcode.min.js"></script>

ok, no error 'Unexpected token <' dispaly.

here is a another problem happened,it is upsetting to me .

online build product tests that dispaly I can't access this site and get resource. OMG ! ok, I change this src again like this:

<script src="./static/js/qrcode.min.js"></script>

and then make some changes in vue.config.js like this:

baseUrl:'./'
assetsDir:'./'

so,online everything is ok ,but in my local project run it will get this error.

finally,I find this :

online url address: http://xxxxx.cn/test0001/#/

local url address: http://192.168.5.108:9000/test0001/#/

(ps:test0001 params can't remove,my project need it)

if I remove this params 'test0001', this error isn't display in my local project test .

I guess build and development environment's difference cause this error,and my params test0001 in url address.

finally,I just use a param to diff this product and development to solve it.

if someone meet this problem like me , please share your solution.

Solution 6:[6]

Uninstalling both CLI's and reinstalling V3 + A 'hard' refresh in Chrome did the trick. Maybe a hard refresh alone was enough (CTRL + F5)

Solution 7:[7]

I assume you are using the same console window that you used for vue ui or vue create to start the project?

Then try to open a new console instance and run your project in it.

In my case it worked and the problem was a overwriten enviroment variable in the first console.

Wish you luck!

Solution 8:[8]

I got this error when I tried to run vue ui. This happened when I installed vue cli 2.0 along with 3.0.

So i uninstalled both and installed 3.0 and then:

All I had to do was a empty cache and hard reload in chrome.

Open up the developer tools by pressing f12 and then click and hold the refresh button then select empty cash and hard reload.

I am not sure if this is related to your specific issue.

Solution 9:[9]

it indicate that the error happened at the first line of app.js, but I check in console the < is actually from index.html. Which means somewhere along the process, the webpack thought index.html should be transpile as app.js.

In my case it was the contrary : I add an url rewrite issue. A to much broad rule made that my js and css assets were redirected to index.html, that's why I add a < at the beginning of my js or css files.

So if it's also the case for you, the problem is in your backend (Java Spring and javax.Filter for the urlrewrite for me). So if it can help someone, here's the correct part of urlrewrite.xml :

<rule match-type="wildcard">
  <from>/assets/**</from>
  <to last="true">-</to>
 </rule>

 <rule match-type="wildcard">
   <from>/index.html</from>
     <to last="true">-</to>
 </rule>

 <rule match-type="wildcard">
   <from>/**</from>
     <to>/index.html</to>
 </rule>

Solution 10:[10]

I had the same error when I tried to link the javascript file to the index.html.

Configuration: Django (Backend) - Vue (Frontend) - Daphne - Nginx.

Django urls.py routes each connection (except prior defined ones e.g. API) to the index.html through a defined view to 'vuejs/index.html'. The javascript file needs to be incorporated through {% include "path" %} and gets rendered through Django. The double curly braces {{}} mean something to Django, which is the reason why the delimiters need to be changed to ['[[', ']]'] inside the Javscript file (see main.js).

vuejs/index.html:

<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
<div id="vue-app">
[[name]]
</div>
<script>
{% include "vuejs/src/main.js" %}
</script>
</body>
</html>

vuejs/src/main.js:

new Vue({
delimiters: ['[[', ']]'],
el: '#vue-app',
data: {
name: 'Vodka Gorbatschow',
}
});

Solution 11:[11]

I had the same issue when deploying to a sub directory on our Azure web server using Vue CLI 3.10. Our site was fine until we changed the routing from history to hash mode which caused this error.

I had to change the links in the index.html page to get it working.

The deployment build gives you this...

<link href=/css/chunk-095570c7.ceb55529.css rel=prefetch>

…but we had to change it to the following for it to work...

<link href="css/chunk-095570c7.ceb55529.css" rel=prefetch>

Solution 12:[12]

Ran into this error randomly with Vue CLI 3 using serve + version 4.1 with all the CLI plugins.

Event though I have Disabled Cache enabled in the web browsers inspection tools I had to resolve this for local development by clearing a Cache Storage:

Open Inspection Tools > Application (tab) > Cache Storage (tree) > Right Click Delete on an entry that has a label ending with http://localhost:8080.

I did not try Right Click on Cache Storage > Refresh Caches, might also work?

If you are having this issue in production, this is not the answer for you, you need to resolve this in some other manner to ensure your app functions for your end users who wont know to do this...

Solution 13:[13]

I had the same problem. For me I solve it by adding the 'asset'

<script src="{{ asset('js/app.js') }}" defer></script>

Solution 14:[14]

I met the same error here, it's just my case happened when I deploy the app, it works good on local env.
After some search, I followed vue-cli's official guidance on publicPath below:

You will need to set publicPath if you plan to deploy your site under a sub path, for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/, then publicPath should be set to "/bar/". In most cases please use '/' !!! Detail: https://cli.vuejs.org/config/#publicpath

I change publicPath from '/' to '/bar/' and the error disappears.

Solution 15:[15]

I had the same problem while trying to deploy Vue 3 application. It looked like all the files were got with 200 status, but in reality it was just an index.html page for every file. Browser expected to get .js or .css file but got something started from <html><head> ...etc. That's why it showed error "unexpected token <". I fixed it providing static path to files like this

app.use(express.static(__dirname + "/dist"));

app.get("*", function(req, res) {
    res.sendFile(__dirname + "/dist/index.html");
});

You can check if your files downloaded correctly by putting their URL in address bar. Browser should show their content correctly. If you see empty page, it means you get something else, even if in Network tab you see 200 status.

Solution 16:[16]

I used also this setup, mentioned above and it suddenly caused the same error (after restarting my mac, I know that sounds weird but the packages update I made are longer ago):

// vue.config.js
module.exports = {
  publicPath: process.env.NODE_ENV === 'production'
    ? '/something/'
    : '/'
};

after changing the '/' to '' everything worked normal again.

Solution 17:[17]

I had the same when building Single page application using Vue Js.

What I noticed is that is not pointing to the right part. The file is missing. So just check if the file exists in the static/Js folder.

Or check the pointer to make sure you are pointing to the right file.

Solution 18:[18]

In the file vue.config.js, make sure to have:

module.exports = {
  publicPath: '/',
};

Solution 19:[19]

I had a similar issue with my Vue site. Locally it worked fine, but once published, I would get 404 errors when refreshing URLs. It had to do with rewriting the path for the API. I followed the Vue Router instructions here... https://router.vuejs.org/guide/essentials/history-mode.html#internet-information-services-iis

...but it still wasn't working. I had to exclude the js/css/img directories from the redirect also.

  <rewrite>
      <rules>
          <rule name="Handle History Mode and custom 404/500" stopProcessing="true">
              <match url=".*" />
              <conditions logicalGrouping="MatchAll">
                  <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                  <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                  <add input="{REQUEST_URI}" pattern="/js/*" negate="true" />
                  <add input="{REQUEST_URI}" pattern="/css/*" negate="true" />
                  <add input="{REQUEST_URI}" pattern="/fonts/*" negate="true" />
                  <add input="{REQUEST_URI}" pattern="/img/*" negate="true" />
                  <add input="{REQUEST_URI}" pattern="/lib/*" negate="true" />
              </conditions>
              <action type="Rewrite" url="/" />
          </rule>
      </rules>
  </rewrite>