2

I am trying to compile an app.js file

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

console.log('test');

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

I am using Visual Studio Code and my package.json is:

    {
  "name": "reactapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "@babel/cli": "^7.0.0",
    "@babel/core": "^7.1.2",
    "@babel/preset-env": "^7.1.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^8.0.4",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-react-app": "^6.1.0",
    "react": "^16.6.0",
    "react-dom": "^16.6.0"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "babel src -d compiled"
  },
  "author": "",
  "license": "ISC"
}

When running npm run build I get:

SyntaxError: Unexpected token (24:4) for <h1>Hello, world!</h1>

my .babelrc file is

{
    "presets": [
        "@babel/preset-env"        
    ]
}

Clarification: I am not using Webpack.

https://babeljs.io/repl compiles the code correctly so I am pretty sure there is nothing wrong with the code itself. Feel free to review it anyway.

Can you please identify the error? Is any dependancy missing or unneeded? Thank you very much.

Giannis Dallas
  • 648
  • 2
  • 8
  • 27

2 Answers2

2

For everyone's information, I found the answer. The .babelrc needs to be

{
    "presets": [
        "@babel/react"        
    ]
}
Giannis Dallas
  • 648
  • 2
  • 8
  • 27
0

What file extension do you use when creating a jsx file? I'm pretty sure you did [filename].jsx instead of [filename].js

You can use this extension but you need to add this in your webpack config

Webpack Config:

   {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
            presets: ['react', 'es2015']
        }
    }

if you prefer .babelrc then

{
  "presets": ["react", "es2015"],
}
William
  • 1,107
  • 2
  • 11
  • 18
  • Thank you, but I am not using Webpack. also my file is `app.js` – Giannis Dallas Nov 04 '18 at 13:44
  • @GiannisDallas Please have a look at https://stackoverflow.com/questions/36609910/react-without-webpack – William Nov 04 '18 at 14:35
  • 1
    Should the order of the presents be the other way around: `["es2015", "react"]`? So that the React transpilation goes before es2015 (since presets are applied in [reverse order](https://stackoverflow.com/a/39798873/4579279)). – Nil Feb 05 '19 at 15:43