0
votes

I am trying to setup boilerplate code for an app using react and webpack. I was able to get webpack setup by the webpack documentation. Next I tried to get Babel working as a "loader" for transpiling the JSX. There are instructions to do this in the same link above but it seems the documentation was incomplete. In order to get react working in addition to the above instructions I had to run "npm install babel-preset-react" and then add "react" and "es2015" to the query parameters in my loader configuration. However as soon as I add the "es2015" I start getting runtime errors saying "Uncaught Reference Error: cats is not defined" in the browser console.

Why is including an es2015 loader causing the require function to stop working?

webpack.config.js

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

var BUILD_DIR = path.resolve(__dirname, 'build');
var APP_DIR = path.resolve(__dirname, 'src/jsx');

module.exports = {
    entry: APP_DIR + '/index.jsx',
    output: {
        path: BUILD_DIR,
        filename: 'app.bundle.js',
    },
    module: {
        loaders: [
            {
                test: /\.jsx$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel', // 'babel-loader' is also a valid name to reference
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    }
}

cats.jsx

var cats = ['dave', 'henry', 'martha'];
module.exports = cats;

index.jsx

cats = require('./cats.jsx');
console.log(cats);

import React from 'react';
import ReactDOM from 'react-dom';
import {render} from 'react-dom';

package.json

{
  "name": "react-webpack",
  "version": "1.0.0",
  "description": "boilerplate for react and webpack",
  "main": "index.html",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "license": "MIT",
  "devDependencies": {
    "babel-core": "^6.14.0",
    "babel-loader": "^6.2.5",
    "babel-preset-es2015": "^6.14.0",
    "babel-preset-react": "^6.11.1",
    "react": "^15.3.1",
    "react-dom": "^15.3.1",
    "webpack": "^1.13.2"
  },
  "private": "true",
  "dependencies": {
    "babel-core": "^6.14.0",        
    "babel-loader": "^6.2.5",
    "babel-preset-es2015": "^6.14.0",
    "babel-preset-react": "^6.11.1",
    "react": "^15.3.1",
    "react-dom": "^15.3.1"
  }
}
1
Shot in the dark here, but I had to also use stage-0 for my webpack.config.js file to work properly. "presets": ["react", "es2015", "stage-0"]justDan

1 Answers

1
votes

I see now, you have:

   cats = require('./cats.jsx');
   console.log(cats);

It should be:

  var cats = require('./cats.jsx');
  console.log(cats);

Or even better:

  const cats = require('./cats.jsx');
  console.log(cats);