Blargian
Blargian

Reputation: 350

Babel doesn't recognise React component

I'm trying to use babel to compile some React code into javascript. My project directory is setup like this:

Project directory

In my App.jsx file under src I have:

const continents = ['Africa','America','Asia','Australia','Europe'];
const helloContinents = Array.from(continents, c => `Hello ${c}!`);
const message = helloContinents.join(' ');

const element = (
  <div title="Outer div">
    <h1>{message}</h1>
  </div>
);

ReactDOM.render(element, document.getElementById('contents'));

I have added a babel.rc file under src and it contains

{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "ie": "11",
        "edge": "15",
        "safari": "10",
        "firefox": "50",
        "chrome": "49"
      }
    }],
    "@babel/preset-react"
  ]
}

And my package.json file looks like:

{
  "name": "pro-mern-stack-2",
  "version": "1.0.0",
  "description": "learning MERN",
  "main": "index.js",
  "scripts": {
    "start": "node server/server.js",
    "test": "echo \"Error: no test specified\" && exit 1",
    "compile": "babel src --out-dir public"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "@babel/cli": "^7.2.3",
    "@babel/core": "^7.2.2",
    "@babel/preset-env": "^7.2.3",
    "@babel/preset-react": "^7.9.4",
    "babel-preset-react": "^6.24.1"
  }
}

When I run npm run compile I get the following error:

> [email protected] compile /home/vagrant/pro-mern-stack-2
> babel src --out-dir public

SyntaxError: src/App.jsx: Unexpected token (6:2)
  4 |
  5 | const element = (
> 6 |   <div title="Outer div">
    |   ^
  7 |     <h1>{message}</h1>
  8 |   </div>
  9 | );
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] compile: `babel src --out-dir public`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] compile script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/vagrant/.npm/_logs/2020-05-23T13_50_03_224Z-debug.log
vagrant@scotchbox:~/pro-mern-stack-2$

App.js is produced under public however the React component is commented out. To the best of my knowledge I have included everything I need for this to work. Any help would be appreciated.

Upvotes: 1

Views: 818

Answers (1)

Kenny Meyer
Kenny Meyer

Reputation: 8027

It's not called babel.rc, but .babelrc, also your .babelrc must be in the root directory of your project, not in in your src/ directory.

Upvotes: 2

Related Questions