Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack babel loader fails to compile jsx

I'm trying to run a simple boilerplate for react + webpack + hot module replacement. But I'm actually stuck on babel/jsx step and need help. I'm following this article.

Currently I've got:

webpack.config.js:

module.exports = {
  context: __dirname + "/app",
  entry: "./app.js",

  output: {
    filename: "app.js",
    path: __dirname + "/dist",
  },

  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loaders: ["babel-loader"],
      }
    ],
  },
}

app/app.js:

import React from "react";
import Greeting from "./greeting";

React.render(
  <Greeting name="World"/>,
  document.body
);

and app/greetings.js:

import React from "react";

export default React.createClass({
  render: function() {
    return (
      <div className="greeting">
        Hello, {this.props.name}!
      </div>
    );
  },
});

and this in package.json:

  "devDependencies": {
    "babel-core": "^6.18.0",
    "babel-loader": "^6.2.7",
    "webpack": "^1.13.3"
  },
  "dependencies": {
    "react": "^15.3.2"
  }

When I run just webpack in the console, as the tutorial says, it should run webpack (and babel underneath) and bundle the whole app, but it doesn't - instead, it throws following error:

$ webpack
Hash: 9a56cc72acac2de6f40c
Version: webpack 1.13.3
Time: 543ms
    + 1 hidden modules

ERROR in ./app.js
Module build failed: SyntaxError: C:/Users/abc/Tests/webpack-react-hmr/app/app.js: Unexpected token (7:2)

   5 |
   6 | React.render(
>  7 |   <Greeting name="World"/>,
     |   ^
   8 |   document.body
   9 | );
  10 |

I'm new to this topic, so I don't know what the problem is, but surely, webpack can't understand JSX syntax. Maybe this part of the tutorial is either wrong or out of date:

Fortunately the Babel loader supports transforming both ES2015 and JSX which means we can get away with using a single loader instead of requiring both the babel-loader and the jsx-loader.

We can install the babel loader with the following command:

npm install babel-loader --save-dev

What should I do in order to fix the webpack/jsx/babel setup?

like image 799
ducin Avatar asked Oct 30 '22 17:10

ducin


1 Answers

You need babel presets to compile react and other ES6, ES7 features.

The list of required presets:

  1. latest
  2. react
  3. stage-0

Add this file as .babelrc to your root.

{
 "presets": ["latest", "react", "stage-0"],
}

and do this installation

npm install --save-dev babel-preset-latest babel-preset-react babel-preset-stage-0

Now, run webpack. It should work!

like image 121
Pranesh Ravi Avatar answered Nov 10 '22 16:11

Pranesh Ravi