最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - require not defined error on bundled JS reactjs - Stack Overflow

programmeradmin1浏览0评论

I'm new to Django and ReactJS, was trying to pile a simple JSX code to JS using this tutorial : .html Didn't work, so I used npm run dev to pile, now it worked but giving error in browser console : Uncaught ReferenceError: react is not defined Here is my webpack.config.js

    var path = require('path');
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var nodeExternals = require('webpack-node-externals');


module.exports = {
    //the base directory (absolute path) for resolving the entry option
    context: __dirname,
    //the entry point we created earlier. Note that './' means
    //your current directory. You don't have to specify the extension  now,
    //because you will specify extensions later in the `resolve` section
    entry: './assets/js/index',

    output: {
        //where you want your piled bundle to be stored
        path: path.resolve('./assets/bundles/'),
        //naming convention webpack should use for your files
        filename: '[name]-[hash].js',
    },
    target: 'node', // in order to ignore built-in modules like path, fs, etc.
    externals: {
    react: 'react'
}, // in order to ignore all modules in node_modules folder

    plugins: [
        //tells webpack where to store data about your bundles.
        new BundleTracker({filename: './webpack-stats.json'}),
        //makes jQuery available in every module
        new webpack.ProvidePlugin({
            //React: "react",
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        })
    ],

    module: {
        loaders: [
            //a regexp that tells webpack use the following loaders on all
            //.js and .jsx files
            {test: /\.jsx?$/,
                //we definitely don't want babel to transpile all the files in
                //node_modules. That would take a long time.
                /*exclude: /node_modules/,*/
                //use the babel loader
                loader: 'babel-loader',
                query: {
                    //specify that we will be dealing with React code
                    presets: ['react']
                }
            }
        ]
    },

    resolve: {
        //tells webpack where to look for modules
        modulesDirectories: ['node_modules'],
        //extensions that should be used to resolve modules
        extensions: ['', '.js', '.jsx']
     }
    }

And assets/bundles/index.js

    var React = require('react')
    var ReactDOM = require('react-dom')
    //snaha//
    var BooksList = React.createClass({
    loadBooksFromServer: function(){
        console.log(123454657);
        $.ajax({
            url: this.props.url,
            datatype: 'json',
            cache: false,
            success: function(data) {
                this.setState({data: data});
            }.bind(this)
        })
    },

    getInitialState: function() {
        return {data: []};
    },

    ponentDidMount: function() {
        this.loadBooksFromServer();
        setInterval(this.loadBooksFromServer,
                    this.props.pollInterval)
    },
    render: function() {
        if (this.state.data) {
            console.log('DATA!')
            var bookNodes = this.state.data.map(function(book){
                return <li> {book.title} </li>
            })
        }
        return (
            <div>
                <h1>Hello React!</h1>
                <ul>
                    {bookNodes}
                </ul>
            </div>
        )
      }
   })

     ReactDOM.render(<BooksList url='/api/' pollInterval={1000} />,
    document.getElementById('container'))

And templates/body.html

    {% load render_bundle from webpack_loader %}
    <!doctype html>
    <html>
    <head>
     <script src=".14.7/react-with-addons.js"></script>
   <script src=".14.7/react-dom.js"></script>
     <meta charset="UTF-8">
     <title>Hello React
        {% block content %}
            {{ id }}
        {% endblock %}
     </title>
      </head>
      <body>
     <div id="container"></div>
      {% render_bundle 'main' %}
      </body>
      </html>

Anything I'm missing? here is my Django project structure

I'm new to Django and ReactJS, was trying to pile a simple JSX code to JS using this tutorial : http://geezhawk.github.io/2016/02/02/using-react-with-django-rest-framework.html Didn't work, so I used npm run dev to pile, now it worked but giving error in browser console : Uncaught ReferenceError: react is not defined Here is my webpack.config.js

    var path = require('path');
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var nodeExternals = require('webpack-node-externals');


module.exports = {
    //the base directory (absolute path) for resolving the entry option
    context: __dirname,
    //the entry point we created earlier. Note that './' means
    //your current directory. You don't have to specify the extension  now,
    //because you will specify extensions later in the `resolve` section
    entry: './assets/js/index',

    output: {
        //where you want your piled bundle to be stored
        path: path.resolve('./assets/bundles/'),
        //naming convention webpack should use for your files
        filename: '[name]-[hash].js',
    },
    target: 'node', // in order to ignore built-in modules like path, fs, etc.
    externals: {
    react: 'react'
}, // in order to ignore all modules in node_modules folder

    plugins: [
        //tells webpack where to store data about your bundles.
        new BundleTracker({filename: './webpack-stats.json'}),
        //makes jQuery available in every module
        new webpack.ProvidePlugin({
            //React: "react",
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        })
    ],

    module: {
        loaders: [
            //a regexp that tells webpack use the following loaders on all
            //.js and .jsx files
            {test: /\.jsx?$/,
                //we definitely don't want babel to transpile all the files in
                //node_modules. That would take a long time.
                /*exclude: /node_modules/,*/
                //use the babel loader
                loader: 'babel-loader',
                query: {
                    //specify that we will be dealing with React code
                    presets: ['react']
                }
            }
        ]
    },

    resolve: {
        //tells webpack where to look for modules
        modulesDirectories: ['node_modules'],
        //extensions that should be used to resolve modules
        extensions: ['', '.js', '.jsx']
     }
    }

And assets/bundles/index.js

    var React = require('react')
    var ReactDOM = require('react-dom')
    //snaha//
    var BooksList = React.createClass({
    loadBooksFromServer: function(){
        console.log(123454657);
        $.ajax({
            url: this.props.url,
            datatype: 'json',
            cache: false,
            success: function(data) {
                this.setState({data: data});
            }.bind(this)
        })
    },

    getInitialState: function() {
        return {data: []};
    },

    ponentDidMount: function() {
        this.loadBooksFromServer();
        setInterval(this.loadBooksFromServer,
                    this.props.pollInterval)
    },
    render: function() {
        if (this.state.data) {
            console.log('DATA!')
            var bookNodes = this.state.data.map(function(book){
                return <li> {book.title} </li>
            })
        }
        return (
            <div>
                <h1>Hello React!</h1>
                <ul>
                    {bookNodes}
                </ul>
            </div>
        )
      }
   })

     ReactDOM.render(<BooksList url='/api/' pollInterval={1000} />,
    document.getElementById('container'))

And templates/body.html

    {% load render_bundle from webpack_loader %}
    <!doctype html>
    <html>
    <head>
     <script src="https://cdnjs.cloudflare./ajax/libs/react/0.14.7/react-with-addons.js"></script>
   <script src="https://cdnjs.cloudflare./ajax/libs/react/0.14.7/react-dom.js"></script>
     <meta charset="UTF-8">
     <title>Hello React
        {% block content %}
            {{ id }}
        {% endblock %}
     </title>
      </head>
      <body>
     <div id="container"></div>
      {% render_bundle 'main' %}
      </body>
      </html>

Anything I'm missing? here is my Django project structure

Share Improve this question asked Mar 28, 2016 at 7:19 Shubhabrata NahaShubhabrata Naha 731 silver badge9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Finally I've solved it! Problem was : it was trying to get variable react where as React.js on browser was providing variable React! So I simple change of externals of webpack.config.js to

    externals: {
    React: 'react'
},

solved the issue!

Next Problem Faced :

"process was not defined"

Solution : added

var env = process.env.WEBPACK_ENV;

to top of webpack.config.js and

new webpack.DefinePlugin({
  'process.env.NODE_ENV': '"production"'
}),
     new webpack.DefinePlugin({
  'process.env': {
    'NODE_ENV': '"production"'
  }
})

into the plugins part of model.export

So Final webpack.config.js would be :

    var path = require('path');
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var nodeExternals = require('webpack-node-externals');
var env = process.env.WEBPACK_ENV;


module.exports = {
    //the base directory (absolute path) for resolving the entry option
    context: __dirname,
    //the entry point we created earlier. Note that './' means
    //your current directory. You don't have to specify the extension  now,
    //because you will specify extensions later in the `resolve` section
    entry: './assets/js/index',

    output: {
        //where you want your piled bundle to be stored
        path: path.resolve('./assets/bundles/'),
        //naming convention webpack should use for your files
        filename: '[name]-[hash].js',
    },
    target: 'node', // in order to ignore built-in modules like path, fs, etc.
    externals: {
    React: 'react'
}, // in order to ignore all modules in node_modules folder

    plugins: [
        //tells webpack where to store data about your bundles.
        new BundleTracker({filename: './webpack-stats.json'}),
        //makes jQuery available in every module
        new webpack.ProvidePlugin({
            //React: "react",
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        }),
         new webpack.DefinePlugin({
      'process.env.NODE_ENV': '"production"'
    }),
         new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': '"production"'
      }
    })
    ],

    module: {
        loaders: [
            //a regexp that tells webpack use the following loaders on all
            //.js and .jsx files
            {test: /\.jsx?$/,
                //we definitely don't want babel to transpile all the files in
                //node_modules. That would take a long time.
                /*exclude: /node_modules/,*/
                //use the babel loader
                loader: 'babel-loader',
                query: {
                    //specify that we will be dealing with React code
                    presets: ['react']
                }
            }
        ]
    },

    resolve: {
        //tells webpack where to look for modules
        modulesDirectories: ['node_modules'],
        //extensions that should be used to resolve modules
        extensions: ['', '.js', '.jsx']
    }
}

Now Enjoy React! Happy Coding :-)

Can you look if you have all the requirements installed.

Look inside package.json. You should have react noted in requirements if you do run.

npm install

If you don't, then run

npm install react --save

ps: in my option if you are running Webpack try to add babel to Webpack presets and write javascript in ES2015 specification.

发布评论

评论列表(0)

  1. 暂无评论