Encountering an issue while using Vue CLI where the console displays an error message: "Uncaught

My project was initially set up using vue-cli 3.0 and everything was running smoothly. However, when I terminated it with <ctrl>-c and tried running npm run serve again, I kept encountering the following error:

Uncaught SyntaxError: Unexpected token <

The error pointed to the first line of app.js, but after checking the console, I realized that the < was actually coming from index.html. This suggested that somewhere in the process, webpack mistakenly treated index.html as if it should be transpiled as part of app.js.

Here are the packages I am currently 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

Is there a way to resolve this issue?

Update01 I ended up deleting the entire node-modules folder and performing a fresh npm install, which seemed to fix the problem. However, if anyone has any insights on why this occurred in the first place, please feel free to share.

Answer №1

For a potential solution, consider inserting <base href="/" /> within the <head> section of your index.html file. This change may resolve the issue you are facing. Best of luck!

Answer №2

If you've been using the "./" prefix for Relative path in the src attributes of your index.html, simply switch it out with "<%= BASE_URL %>" and everything should function correctly.

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

While using "./" may not cause issues with regular Vue Routing, it can lead to trouble with Dynamic Route Matching ({ path: '/user/:id', component: User }) especially when referring to files in your index.html.

This is because in the Vue file structure, dependencies are placed inside the route folder like

user/js/config.js

Even when your route includes parameters (), due to Dynamic Route Matching and the use of the same Vue component (User.vue), the file structure remains constant.

In such cases, using "./" might inadvertently lead to user/1234/js/config.js which could result in a default 404 page appearing. This error originates from the fact that the referenced file begins with "< html >", hence triggering a "Uncaught SyntaxError: Unexpected token <" on line 1.

Answer №3

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

To customize your webpack configuration, you should modify the publicPath property in your webpack.config.js file.

provides a solution that works if your application is hosted at http://example.com

However, if your application is hosted at http://example.com/something

You will need to manually adjust the public path every time you deploy, which can be quite inconvenient.

To set the publicPath dynamically based on the environment, you can update your vue.config.js file like this:

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

Answer №4

I encountered a similar issue and attempted to fix it by removing node modules and reinstalling npm, but unfortunately, that did not resolve the problem.

What did end up working for me was clearing all site data. If you are using Chrome, you can accomplish this by navigating to the development tab (Ctrl+Shift+i), accessing the 'application' tab, selecting "Clear storage" on the side panel, and then clicking on the "Clear site data" button.

My assumption is that there may have been an old service-worker interfering with the request and causing it to serve the html file instead of the app.js. If you have previously utilized PWA's at the URL "http://localhost:8080," this solution may help resolve the issue.

Answer №5

Encountering the same issue here. Within the index.html file, I included the script tag as follows:

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

Upon modifying the src attribute to:

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

No longer was the 'Unexpected token <' error visible.

However, a separate issue arose that left me feeling frustrated.

During online product testing, I encountered difficulties accessing the site and retrieving resources. To rectify this, I reverted the src back to:

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

Additionally, I made adjustments within vue.config.js like so:

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

Subsequently, everything functioned flawlessly online. Nevertheless, running the local project triggered an error.

After thorough investigation, I discovered the following:

Online URL:

Local URL:

(note: test0001 params are essential for my project)

Upon removing the 'test0001' parameter, the error ceased to manifest during local testing.

It is likely that the disparity between build and development environments, along with the presence of the 'test0001' parameter in the URL, contributed to this issue.

Ultimately, I resorted to utilizing a parameter to distinguish between the production and development versions as a workaround.

If anyone else encounters a similar dilemma, I urge you to share your solution.

Answer №6

After removing the previous versions of the CLI and reinstalling V3, combined with performing a 'hard' refresh in Chrome, everything started working correctly. It's possible that just doing a hard refresh (CTRL + F5) may have been sufficient.

Answer №7

Ensure that your vue.config.js file includes the following:

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

Answer №8

Are you utilizing the identical console window that was used for initiating the project with vue ui or vue create?

If so, consider opening a fresh console instance and executing your project within it.

In a similar situation, this approach resolved the issue caused by an overridden environment variable in the initial console.

Best of luck to you!

Answer №9

When attempting to launch vue ui, I encountered an error. This problem arose after installing both vue cli 2.0 and 3.0.

To resolve the issue, I uninstalled both versions and only kept 3.0. Following that, I simply had to clear the cache and perform a hard reload in Google Chrome.

To do this, I accessed the developer tools by pressing f12, then clicked and held the refresh button. From there, I selected the option to empty the cache and perform a hard reload.

It's worth noting that this solution may not apply to your specific situation.

Answer №10

It seems like the error is pointing to the first line of app.js, but upon checking the console, it was actually from index.html. This suggests that at some point during the process, webpack interpreted index.html as app.js.

In my situation, the issue was the opposite: I encountered a URL rewrite problem. A overly broad rule caused my JS and CSS assets to be redirected to index.html, resulting in a leading < in my JS and CSS files.

If you are experiencing a similar issue, the root of the problem may lie in your backend code (in my case, Java Spring and javax.Filter for URL rewrite). Here is the corrected section of the urlrewrite.xml that resolved the issue:

<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>

Answer №11

I encountered a similar issue while attempting to connect the javascript file to the index.html.

Setup: Backend using Django, Frontend with Vue, Daphne, and Nginx.

In Django's urls.py, all connections (excluding pre-defined ones like API) are directed to index.html via a specified view to 'vuejs/index.html'. The javascript file must be included using {% include "path" %} and rendered through Django. The use of double curly braces {{}} has significance in Django, which is why the delimiters have to be adjusted to ['[[', ']]'] within the Javascript file (refer to main.js).

vuejs/index.html:

<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98eeedfdd8aab6aeb6a9a8">[email protected]</a>/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',
}
});

Answer №12

Encountering the same issue while deploying to a subdirectory on our Azure web server with Vue CLI 3.10 was a challenge. The site functioned well until we switched the routing from history to hash mode, triggering an error.

To resolve this issue, modifications to the links in the index.html page were necessary.

During the deployment build, we observed the following output...

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

...but for it to function correctly, adjustments were essential, as seen below...

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

Answer №13

Encountered an unexpected error while working with Vue CLI 3 and using serve + version 4.1 along with all the CLI plugins.

Even though I had Disabled Cache activated in the web browsers' inspection tools, I had to address this issue for local development by clearing the Cache Storage:

To resolve this, navigate to Inspection Tools > Application (tab) > Cache Storage (tree) > Right Click and select Delete on an entry with a label ending in http://localhost:8080.

I have not attempted Right Click on Cache Storage > Refresh Caches, which might also be effective?

If you are experiencing this issue in a production environment, this solution may not be suitable. You will need to address this in a different way to ensure the proper functioning of your application for end users who may not know how to perform these steps...

Answer №14

Encountered a similar issue but was able to fix it by including the 'asset'

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

Answer №15

Encountered a similar issue myself, but the error only occurred when deploying the application, it functioned properly in the local environment.
After conducting some research, I decided to follow the official guidelines from vue-cli regarding the publicPath:

If you intend to deploy your site under a subpath, such as GitHub Pages, you will need to set publicPath. For example, if you plan to deploy your site to , then publicPath should be set to "/bar/". In most cases, it is recommended to use '/' !!! For more details, refer to: https://cli.vuejs.org/config/#publicpath

By changing the publicPath from '/' to '/bar/', I was able to resolve the error.

Answer №16

When I was attempting to deploy my Vue 3 application, I encountered a similar issue. Despite all the files appearing to be received with a 200 status, they were actually just index.html pages for each file. It seemed like the browser was expecting .js or .css files but instead received content starting with <html><head>...etc. This resulted in an error displaying "unexpected token <". To resolve this, I made sure to provide a static path to the files as shown below:

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

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

To verify if the files were downloaded correctly, you can enter their URLs in the address bar. The browser should display their content accurately. If you see an empty page, it indicates that something else is being retrieved, even if the Network tab shows a 200 status.

Answer №17

After following the setup mentioned earlier, I encountered the same error unexpectedly (even though I had restarted my computer; it may sound strange, but the package updates I had performed were done a while ago):

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

However, once I changed '/' to '', everything started working normally again.

Answer №18

While working on a Single Page Application with Vue Js, I encountered a similar issue.

Upon closer inspection, I realized that the path was incorrect. It seems that the file is missing. I recommend verifying if the file actually exists in the static/Js folder.

Alternatively, double check the pointer to ensure it is directed to the correct file.

Answer №19

My Vue website was running smoothly on my local server, but I encountered a frustrating issue once I published it - 404 errors would occur when trying to refresh URLs. After some investigation, I discovered that the problem stemmed from the path being rewritten for the API. I decided to follow the instructions provided on the Vue Router website at the following link: https://router.vuejs.org/guide/essentials/history-mode.html#internet-information-services-iis

Despite following the guidelines, I still faced difficulties getting it to work properly. Eventually, I realized that I needed to exclude certain directories like js, css, and img from the redirect as well.

  <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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Failure to establish connection between electron/socket.io client and python-socketio/aiohttp server

My websocket connection is failing at the moment, even though it was working perfectly just a couple of days ago. I attempted to fix the issue by downgrading electron from version 6 to 5.0.6, but unfortunately, this did not resolve the problem. https://i. ...

The retrieval of JSON file using $.GetJson() is unsuccessful from local directory

There is a basic autocomplete program in place. The data entered in the textbox is successfully captured while debugging, however, the GetJson() function fails to retrieve the JSON file, causing the program to malfunction. Here's the relevant code sn ...

Error message encountered in PHP due to an undefined index

My goal is to add items from a form to a table named products. The form layout can be seen here: https://i.stack.imgur.com/f9e08.png The "Add more suppliers: +" link adds a new row to the form when clicked. The corresponding script for this action is as ...

Retrieving data from varied React components - triggered by clicking a LOG button

function Copy() { const Message = "MESSAGE"; const [messageList, setMessageList] = useState([{ text: "Hello", id: 1 }]); const [newMessageValue, setNewMessageValue] = useState(0); const addToMessageList = () => { alert(n ...

Battle between Comet and Ajax polling

I'm looking to develop a chat similar to Facebook's chat feature. Using Comet would require more memory to maintain the connection. There seems to be a latency issue when using Ajax polling if requests are sent every 3-4 seconds. Considering t ...

How to determine the presence of 'document' in Typecsript and NextJS

Incorporating NextJS means some server-side code rendering, which I can manage. However, I'm facing a challenge when trying to check for set cookies. I attempted: !!document && !!document.cookie as well as document !== undefined && ...

Executing API calls utilizing Axios in a NodeJS environment with the Authorization Basic feature

I have developed an API to retrieve a token from PayPal. curl -v POST https://api.sandbox.paypal.com/v1/oauth2/token \ -H "Accept: application/json" \ -H "Accept-Language: en_US" \ -u "CLIENT_ID:SECRET" &b ...

Modifying the default label for each bubble on a bubble chart with chartjs-plugin-datalabels

Is there a way to add labels to each bubble in the bubble chart using chartjs-plugin-datalabels? For every bubble, I'd like to display the label property of each object within the data.dataset array, such as "Grapefruit" or "Lime". Currently, I'm ...

Is it possible to install a Chrome extension specifically for YouTube on Google Chrome?

Hey, I'm trying to eliminate thumbnail images from YouTube. The code I am currently using is: while (true) { $("ytd-thumbnail").remove() } As of now, when I input this code in the console, it successfully removes all thumbnail images. However, I ...

Exploring the capabilities of xhr2 using pure javascript

Currently, I am attempting to utilize xhr2 in order to read through a json file. Despite my efforts in researching various methods to accomplish this task, none have proved successful thus far. The function featured below my require statements is the one t ...

After making an Ajax call using AngularJS in a PHP file, I expected to receive only a success or fail message. Instead, I received the entire HTML page code along

After making an Ajax call using AngularJS in a PHP file, I expected to receive only a success/fail message. However, I ended up receiving the full HTML page code along with tags. Here is my AngularJS code: $http.post('ajax_Location.php',{ &apos ...

Obtain access to the DOM element using template reference variables within the component

Searching for a method to obtain a reference to the DOM element for an Angular 2 component through a template reference variable? The behavior differs when working with standard HTML tags versus components. For example: <!--var1 refers to the DOM node ...

Is there a way to prevent an iframe from being recorded in Chrome's browsing history?

I'm in the process of developing a Chrome extension that inserts an Angular application into the user's browser window to create an interactive sidebar. I've been successful in most of my goals by inserting an iframe through a content script ...

Show search results in real-time as you type

I am currently developing a SharePoint 2007 web part using Visual Studio. The main goal of this web part is to search a SharePoint list and present the results to the user. My objective is to have the results displayed automatically once the user finishes ...

Is there a way to dynamically apply styles to individual cells in a React Table based on their generated values?

I'm having trouble customizing the style of a table using react table, specifically changing the background color of each cell based on its value. I attempted to use the getProps function in the column array as suggested by the react table API documen ...

When no files are uploaded, req.files.upload.length will return zero; however, if more than one file is uploaded, it will return the total number of files. In the

When using this loop, the variable “req.files.upload.length” will return the file count if 0 or more than one files are uploaded. However, it returns the file size if only one file is uploaded. Why does this happen? This is the upload handler: app.po ...

Mastering server requests in Angular 5

I have come across recommendations stating that server requests should be made via services and not components in order to ensure reusability of functions by other components. Ultimately, the server response is needed in the component. My query pertains t ...

Running PHP database commands within JavaScript

My issue involves a list that can have one or more tasks attached to it. Here's how the process works: When a user attempts to delete the list, a PHP code checks the 'tasks' table in MySQL to see if any tasks are linked to the list being d ...

What steps can be taken to address the issue of the body-parser module being disabled in a node

My API is not functioning properly and I have observed that the body-parser module seems to be disabled in some way. Despite my efforts, I have been unable to find any information on this issue. Please refer to the image attached below for further details. ...

The issue arises due to conflicting indent configurations between eslint and @typescript-eslint/indent

Currently, I am using eslint and prettier in a TS express application. I am trying to set the tab width to 4, but it appears that there is a conflict between the base eslint configuration and the typescript eslint. When looking at the same line, this is w ...