GBarroso GBarroso - 2 months ago 7
React JSX Question

Can't set up React/Babel/Webpack

So I was trying to set up the React/Babel/Webpack environment but I had some trouble doing so. I started creating a new folder, did the

npm init
and then I followed everything in this tutorial: https://facebook.github.io/react/docs/package-management.html


  • First, I've installed webpack globally

  • I've created a
    index.js
    with the same content on the tutorial

  • I've created a
    .babelrc
    file with
    { "presets": ["react"] }

  • Ran the
    npm install --save react react-dom babel-preset-react babel-loader babel-core



Then, when I run the command
webpack main.js bundle.js --module-bind 'js=babel-loader'
it gives me an error: "Module parse failed ~ You may need an appropriate loader to handle this file type.

Any idea guys? I've literally copy and pasted every step from the tutorial and I am sure all the files are correct. Thanks in advice!

Answer

Create file webpack.config.js

var path = require('path'); 
var webpack = require('webpack'); 

module.exports = { 
  entry: './main.js', 
  output: { path: __dirname, filename: 'bundle.js' }, 
  module: { 
    loaders: [{ 
      test: /.js?$/, 
      loader: 'babel-loader', 
      exclude: /node_modules/ 
    }] 
  }, 
};

Run

webpack

and it will generate bundle.js for you.

Now make sure you have added index.html

<!DOCTYPE html> 
<html> 
  <head> 
    <meta charset="UTF-8" /> 
    <title>Hello React!</title> 
  </head> 
<body> 
  <div id="example"></div> 
  <script src="bundle.js"></script> 
</body> 
</html>