4
votes

I am learning React and try to create a simple React application. I want to use ES2015 modules and some ES6 features so I installed Babel and browserify via npm.

These are node modules that I installed:

  • babel
  • babel-preset-es2015
  • babel-preset-react
  • babelify
  • browserify
  • gulp
  • reactify
  • vinyl-buffer
  • vinyl-source-stream
  • react
  • react-dom

I want to make script into several files (like itemComponent as React) and merge them into dist/app.js that actually website loads. For this, I used gulp!

This is my gulpfile.js:

var source = require('vinyl-source-stream');
var gulp = require('gulp');
var browserify = require('browserify');
var reactify = require('reactify');
var babelify = require('babelify');

gulp.task('default', function() {
    return browserify('./source/' + file)
    .transform(babelify, { presets: ["es2015", "react"] })
    .bundle()
    .pipe(source(file))
    .pipe(gulp.dest('./dist'));
});

Gulp is actually working well, everything is transpiled good without error. But check the website, it says:

app.js:19474 Uncaught ReferenceError: React is not defined

So I removed react and react-dom installed via npm, and just download React and load from HTML simply just use script tag, and it works. But I want to include react like this:

import React from 'react';

But it is not working. This is my app.js:

import React from 'react';
import ReactDOM from 'react-dom';
import ItemList from './components/itemlist';

let items = [ ... ];

class App extends React.Component {
    render() {
        return (
            <div>
                <h1>List of items:</h1>
                <ItemList items={this.props.items} />
            </div>
        )
    }
}

ReactDOM.render(<App items={items} />, document.getElementById('app'));

I don't know what is the problem and I don't want to load each react file using script tag. Is there something I missed?

1
Are you sure that you import React in all your JSX files? This bug could happens, when JSX transpiled to React.createElement..., and there is no React in local scope. For example, if you have <h1>Hello<h1>, it will be transpiled to React.createElement("h1", null, "Hello"), so you need to be sure, that you have React in scope. - Nikolai Mavrenkov
thanks Nikolai! i forgot to import React each seperated file! it works! - modernator
Please post the solution and mark this question as answered if you're all set. - Joseph Cho

1 Answers

0
votes

Reason of this issue were I forgot to import React module in child components, .

JSX will transpile to something like React.createElement, but there wasn't React exists so that's why I have Reference Error.