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?
You need babel presets to compile react
and other ES6, ES7 features.
The list of required presets:
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With