Using `import React from 'react'` throws Uncaught SyntaxError: Unexpected identifier

I recently set up webpack 3 and babel in my project. My entry file, index.js/bundle.js, is successfully building and running with ES7/8 features. However, I am facing an issue with imports causing an error "

Uncaught SyntaxError: Unexpected identifier
". I have tried configuring babel in both the package.json and a separate .babelrc file in the root directory of my app, but the import statement still throws an error. Is there something missing from my setup?

index.js (works)

// does not work
// import React from 'react' 

// works
const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.values(object1));

webpack.config.js

const path = require('path')

module.exports = {
  context: path.resolve(__dirname, 'app/assets/javascripts/source'),
  entry: './index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'app/assets/javascripts/webpack')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  }
}

.babelrc

{
  "presets": ["env", "react"]
}

package.json

}
  ...
  "license": "MIT",
  "scripts": {
    "build": "webpack",
  },
  "babel": {
    "presets": [
      "env",
      "react"
    ]
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "prop-types": "^15.6.0",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "webpack": "^3.10.0",
    "webpack-dev-server": "^2.11.1"
  }
}

Answer №1

Here's a suggestion: give the transform-es2015-modules-amd plugin a try. It converts ES2015 modules into Asynchronous Module Definition (AMD).

{
    presets: ["env", "react"],
    plugins: ["transform-es2015-modules-amd"]
 }

For more information, visit transform-es2015-modules-amd

Answer №2

The issue lies in the fact that the code is not functioning properly due to the lack of es6 translation support. To resolve this, you must include the babel-preset-es2015.

Additionally, make sure to configure it in your .babelrc file:

{
    "presets":[
        "es2015", "react"
    ]
}

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

Using jQuery to create a script that will transition random images simultaneously within a div

I am currently working on a JavaScript script that will animate 10 images flying into a div, appearing side by side. The goal is to have each image fly in randomly with a unique transition. At the moment, my script is almost complete as I've successf ...

What's the best way to align three images in a row?

I am having trouble centering three social media icons next to each other. I can't seem to figure out the proper way to do it. https://i.stack.imgur.com/Zf5p9.png <div class="maintext flipInX animated"> <div class="socials wow bounce an ...

Ways to extend the waiting timeout from 30000 ms to 60000 ms for npm installation on Ubuntu

Due to the slow internet connection, I was unable to install packages from npm. The issue arose when npm returned an error stating: npm ERR! Response timeout while trying to fetch https://registry.npmjs.org/create-react-app (over 30000ms) I thought tha ...

Custom Native Scrollbar

Currently, there are jQuery plugins available that can transform a system's default scroll bar to resemble the iOS scroll bar. Examples of such plugins include . However, the example code for these plugins typically requires a fixed height in order to ...

Factory not properly updating AngularJS controller

I am facing an issue with two controllers and one factory in my AngularJS application. The first controller sends an http request to a server, receives a string in response, and stores it in the factory. However, the second controller does not update with ...

Customize React Hook Form version 7 by incorporating a unique input method for handling empty values

Introducing my custom Input component: export type InputProps = { error?: string } & InputHTMLAttributes<HTMLInputElement> export const Input: FunctionComponent<InputProps> = ({ error, ...props }) => ( <input {...props} /> ) ...

Transferring data from AJAX to PHP class methods

Q. Is it feasible to transfer data from ajax to a specific php class with functions? For instance, verifying a username on the registration form to check if the user already exists. This form is straightforward and will gather a username input along with ...

The absence of the Three.js file in my HTML file is noticeable

Currently, I am diving into HTML5 and experimenting with the Three.js 3D engine. While following a tutorial from this source, it was recommended that I include the three.js file in my HTML document. However, I encountered two files with the same name and d ...

Activate when every single pixel within an element is see-through

I've designed a web page that includes two canvas elements stacked on top of each other. The purpose of this setup is to allow me to "erase" the top canvas and reveal an image loaded into the bottom canvas. So far, this functionality has been working ...

An error occurred - 0x800a1391 - JavaScript runtime error: The function 'SelectAllCheckBoxes' has not been defined

I'm currently in the process of learning web development and I am trying to incorporate jQuery into my ASP .NET page. Within the header section, I have included the necessary references: <head id="Head1" runat="server"> <link href=" ...

What are the steps to effectively utilize my search bar alongside Google Custom Search?

Here is the HTML code for my form: <form action="#" class="searh-holder"> <input name="se" id="se" type="text" class="search" placeholder="Search.." value="" /> <button class="search-submit" id="submit_btn"><i class="fa fa-sea ...

Ways to retrieve and upload a blob from a file object

After receiving a file object via an HTML input on-change event in my component.html: onFileSelected(event) { this.selectedFile = event.target.files[0]; } Now, I need to send a POST request to upload the image to the database. The database only acc ...

Converting Dates with Ractive.js

Is there a way to transform the Epoch time value retrieved from a JSON endpoint into a readable time string format such as "Tue 19 Jan 11:14:07 SGT 2038" without relying on external libraries like moment.js? var ractive = new Ractive({ el: '#cont ...

Dynamically load content onto a jQuery Mobile page upon clicking a link

I'm relatively new to working with jQuery Mobile and making AJAX requests. Let me try to explain my issue clearly. Currently, I am developing a mobile project and utilizing the jQuery Mobile auto-complete list, populating it with data from an XML fil ...

What is the best way to refresh a div every 20 seconds?

I'm currently working with this script: <script id="_wauwgs">var _wau = _wau || []; _wau.push(["small", "p00ystfryeuc", "wgs"]); (function() {var s=document.createElement("script"); s.async=true; s.src="http://widgets.amung.us/small.js" ...

Using an image tag with dual quotes in Vue.js

I am currently working on a feature where users can upload an image and then have it displayed after the upload is complete. However, I am facing an issue where the response link of the image contains a double quote, and when I use the <img> tag to ...

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

Use a personalized CSS class with the Kendo Dropdown Widget

Is there a way to assign a custom CSS class to the dropdown HTML container that is created when using the .kendoDropDownList() method on a <select> or <input> element? In this fiddle ( http://jsfiddle.net/lav911/n9V4N/ ) you can see the releva ...

Preventing Event Loop Blocking in Node.js: The Key to Streamlining Performance

I am currently working on developing two APIs using Express.js. The tasks for both APIs are quite straightforward. The first API involves running a for loop from 1 to 3,000,000, while the second API simply prints a string in the console. All the necessary ...

Having trouble uploading a file in PDF format (*.pdf)

I'm attempting to use Node's readFile method to read a file and then send it as a response so that the user can download it. This is the code snippet I have: async function(req, res, next) { const query = { id: req.params.id }; // @ts-ignore co ...