I'm getting started with Electron and I'm trying to set up my app to use React. I'm also new to React, Webpack, Babel, NPM...pretty much the whole Node.js ecosystem and build tools. I started from scratch. I think I'm pretty close, but I'm stuck trying to compile my main JSX file:
$ webpack
Hash: fa3346c3ff9bfd21133d
Version: webpack 1.12.14
Time: 41ms
[0] ./js/helloworld.jsx 0 bytes [built] [failed]
ERROR in ./js/helloworld.jsx
Module parse failed: /...path.../js/helloworld.jsx Line 5: Unexpected token <
You may need an appropriate loader to handle this file type.
|
| ReactDOM.render(
| <h1>Hello, world!</h1>,
| document.getElementById('example')
| );
Here's my package.json
:
{
//...
"dependencies": {
"babel-preset-es2015": "~>6.6.0",
"babel-preset-react": "^6.5.0",
"electron-prebuilt": "^0.36.0",
"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-photonkit": "~>0.4.1",
"webpack": "^1.12.14"
}
}
...my .babelrc
:
{
"presets": ["react"]
}
...my webpack.config.js
:
var path = require("path");
module.exports = {
entry: path.resolve(__dirname, "js/helloworld.jsx"),
output: {
path: path.resolve(__dirname, "out"),
publicPath: 'out/',
filename: 'app.js'
},
};
...and the helloworld.jsx
file:
var React = require('react');
var ReactDOM = require('react-dom');
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
What am I doing wrong? How can I get everything configured correctly?
If you work on a React project, chances are you have to deal with Babel. It is needed for 2 main tasks: To compile JSX into React. createElement API calls.
Babel : Babel is a JavaScript compiler that transform the latest JavaScript features, which are not understandable to every browser, into a backward compatible version of JavaScript in current and older browsers or environments. JSX : JSX is a syntactical extension to JavaScript.
There is a specific folder structure to be followed when using Webpack and Babel in your project. We need two separate folders, dist for the output files and src for the input files. You have to keep the index. html file inside the dist folder.
You need to add the babel-loader
so webpack knows to use babel to process your files
$ npm install --save-dev babel-loader
And then in your `webpack.config.js:
module.exports = {
entry: path.resolve(__dirname, "js/helloworld.jsx"),
output: {
path: path.resolve(__dirname, "out"),
publicPath: 'out/',
filename: 'app.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: /node_modules/
}
]
}
};
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