I keep encountering an Uncaught SyntaxError: Unexpected token < error in my bundle.js file

Currently, I am in the process of creating a boilerplate for React web applications.

However, whenever I try to access http://localhost:8080/, I encounter an error stating: Uncaught SyntaxError: Unexpected token < in my bundle.js file.

I'm unsure of what steps to take next and would greatly appreciate any guidance or assistance.

Below are some of the key files involved:

/public/index.html

<!DOCTYPE html>
<html lang="en">

<head>

   <meta charset="UTF-8>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>New app</title>
   <link rel="stylesheet" href="/style.css" />
   <script src="./bundle.js" defer> .</script>
</head>

<body>
   <div id="app"></div>
</body>

</html>

/client/app.js

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <div>Hello, world!</div>,
  document.getElementById('app') 
);

webpack.config.js

module.exports = {
  entry: [
'@babel/polyfill', // enables async-await
'./client/app.js',
  ],
  mode: 'development',
  output: {
    path: __dirname,
    filename: `./public/bundle.js`,
  },
  devtool: 'source-maps',
  module: {
     rules: [
      {
        test: /\.js$/,
         exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
    ],
  },
};

package.json

{
  "name": "boilerplatelivmarx",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server",
    "start-dev": "webpack -w & nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-preset-env": "^1.7.0",
    "babel-preset-stage-2": "^6.24.1",
    "express": "^4.16.4",
    "path": "^0.12.7",
    "react": "^16.6.0",
    "react-dom": "^16.6.0",
    "react-router-dom": "^4.3.1"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-preset-react": "^6.24.1",
    "webpack": "^4.23.1",
    "webpack-cli": "^3.1.2"
  }
}

Your help is really appreciated!

Answer №1

It appears that there is an issue with your jsx processing;

To fix this, you need to add the react preset to your webpack.config.js:

...
use: {
  loader: 'babel-loader',
  options: {
    presets: ['react']
  }
},
...

Additionally, it seems like you are attempting to use @babel/polyfill, but have not installed it yet.

To install it, run:

npm i @babel/polyfill

Also, make sure to remove the dot in the <script> tag in your index.html file:

<!--                             ↓      -->
<script src="./bundle.js" defer></script>

Once these steps are completed, everything should build successfully:

https://i.sstatic.net/aE5Cn.png

Now, you can run it:

https://i.sstatic.net/PHcld.png

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

What is the reason behind certain dependencies being installable with npm and not bower, and the reverse situation as well?

After attempting to install "angular-jk-carousel" using npm, I encountered issues. However, the installation process went smoothly when using bower. Interestingly, the official documentation for "angular-jk-carousel" states that it can be installed using ...

Tips for implementing a handler on a DOM element

$(document).ready(function(){ var ColorBars = document.getElementsByClassName("color-bar"); var number = 0; ColorBars[0].onclick = hideLine(0); function hideLine(index){ var charts = $("#line-container").highcharts(); v ...

Npm installation is incompatible with Ubuntu operating system

I am encountering an issue while attempting to install npm using apt-get. Check out the log provided below: matej@matej-Inspiron-7720:~$ sudo apt-get install npm Reading package lists... Done Building dependency tree Reading state information... ...

How to programmatically close a Bootstrap modal in a React-Redux application using jQuery

Hello everyone, I hope you're all doing well. I am currently working on a React application that utilizes Redux. I have run into an issue while trying to close a modal in Bootstrap programmatically. The versions I am using are Bootstrap 4 and jQuery 3 ...

Unlocking the Secret: How to Bind a Global Touch Event Handler in Angular 4 to Prevent iOS Safari Page Drag

The issue at hand is that within my Angular 4 application, there is a D3.js chart that relies on user touch input for dragging a needle to a specific value. The drag functionality is triggered by 'touchstart', while the registration of the final ...

"In Typescript, receiving the error message "Attempting to call an expression that is not callable" can be resolved

I am in the process of creating a function that matches React's useState signature: declare function useState<S>( initialState: S | (() => S), ): [S, React.Dispatch<React.SetStateAction<S>>]; Below is an excerpt from the functi ...

Upgrade from using fetch to utilize await in order to achieve the same outcome

After transitioning a one-time fetch request code snippet to my API, I encountered the following: let response = await fetch(visitURL, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization& ...

Unleashing the power of jQuery, utilizing .getJSON and escaping

When I use .getJSON, the response I get is a JSON string with many \" characters. However, the callback function does not fire when the page is launched in Chrome. I have read that this happens because the JSON string is not validated as JSON (even th ...

Email attachments not working in Node Mailgun

I am facing an issue with my code that is designed to send emails using Mailgun in Node. The code functions as expected and sends the email successfully; however, it fails to attach the specified files. // pdfA and pdfB are both buffers defined earlier le ...

Sending data from an AJAX request to a Spring controller is a common task in web

var TableDatatablesEditable = function () { var handleTable = function () { function restoreRow(oTable, nRow) { var aData = oTable.fnGetData(nRow); var jqTds = $('>td', nRow); for (var i = 0, ...

What is the reason for the getter not being able to retrieve the value

I am experiencing an issue with a getter that returns an array of objects. The challenge I face is that I need to display past and current warnings in separate components. The getter currently only retrieves the current warning and ignores any past warnin ...

Creating Docker images in a lerna monorepo without the need for publishing

In the context of Lerna monorepos, the primary goal is to facilitate branch building and deployments. The challenge arises from the fact that Lerna monorepos either consolidate dependencies in NPM or utilize yarn workspaces to achieve the same outcome, re ...

How can one retain an outdated NPM package that is no longer available on the NPM repository?

I recently discovered that the package I'm using was removed from NPM and GitHub, but I still have it saved in my node_modules folder. Is there a way for me to preserve this package and continue using it, even if I have to maintain it myself? Addition ...

What steps can be taken to identify the two highest numbers in an array, one being positive and the other

Seeking the optimal solution to resolve this issue Issue: Develop a function called ArrayChallenge (Javascript) that takes a single argument "arr" representing an array of numbers. The function should return the string true if there exist two numbers in t ...

Utilize Apollo to retrieve a variety of queries at once

Currently, I'm utilizing nextJS for my frontend development along with Apollo and GraphQL. For fetching queries, I am using the getStaticProps() function. To enhance modularity and maintainability, I have segmented my queries into multiple parts. The ...

Experiencing a kexec error during npm install process

Encountered the following error messages with node v12.22.7 and npm 6.14.15, as well as with node v16.13.1 and npm v8.1.2: > node-gyp rebuild CXX(target) Release/obj.target/kexec/src/kexec.o ../src/kexec.cc:19:11: error: no member named 'Handle& ...

Calculating the total of fields from populated documents using Mongoose

In my application, I have two main models: User and Track. A User can complete various Tracks and earn points for each one. The schema for the User model looks like this: let userSchema = new mongoose.Schema({ name: {type: String, required: true}, ...

I encountered an issue with the onclick event in JavaScript

I have been struggling with an issue for some time now and I just can't seem to figure out what I am doing wrong. Here's the problem - when I click on a link on my website, a calculator should pop up. Then, when I click the off button on the calc ...

Extract website addresses from a text and store them in an array

I am currently attempting to extract URLs from a string and store them in an array. I have implemented a node module to assist with this task. const getUrls = require("get-urls") url = getUrls(message.content) However, the current implementation fails to ...

Transmit information to the client-side webpage using Node.js

One of the main reasons I am diving into learning Node.js is because I am intrigued by the concept of having the server send data to the client without the need for constant querying from the client side. While it seems achievable with IM web services, my ...