Installing reactJS with django


#1

I was trying to install ReactJS in my django app, but i am completely stuck.

I was following this tutorial:

which all went well. until we had to create webpack.config.js, which i did:

var path = require("path")
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')

module.exports = {
    context: __dirname,

    entry: './static/js/index', // entry point of our app. static/js/index.js should require other js modules and dependencies it needs

    output: {
        path: path.resolve('./static/bundles/'),
        filename: "[name]-[hash].js",
    },

    plugins: [
        new BundleTracker({filename: './webpack-stats.json'}),
    ],

    module: {
        loaders: [
            { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader'}, // to transform JSX into JS
        ],
    },

    resolve: {
        modulesDirectories: ['node_modules', 'bower_components'],
        extensions: ['', '.js', '.jsx']
    },
}

then i try to compile the bundle:

./node_modules/.bin/webpack --config webpack.config.js

but i get:
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.resolve has an unknown property 'modulesDirectories'. These properties are valid:
object { alias?, aliasFields?, cachePredicate?, descriptionFiles?, enforceExtension?, enforceModuleExtension?, extensions?, fileSystem?, mainFields?, mainFiles?, moduleExtensions?, modules?, plugins?, resolver?, symlinks?, unsafeCache?, useSyncFileSystemCalls? }
- configuration.resolve.extensions[0] should not be empty.

Why? I don't understand.... Googling only yields that modulesDirectories should work, can someone help me? If additional information is required i happily provide it.

i forgot the question, why do i get this error and more importantly, how do i fix it?


#2

what is your webpack version? It might be different than it was when the tutorial was written, hence the config file might be a little bit different


#3

i suspected it, i believe the webpack version i use is 3.0, let me verify

but googling this also didn't yield good results, i might have missed it, i was a bit frustrated at that point

webpack@3.0.0 is the webpack version i am using, not sure what tutorial uses

seems a constant problem, many of this guides/tutorials all seem outdated


#4

Try to delete the modulesDirectories line.
https://webpack.js.org/configuration/


#5

then it gives:

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.resolve.extensions[0] should not be empty.

should i remove the whole resolve section?


#6

i removed the first empty extension:

extensions: ['.js', '.jsx']

seems to do the trick, are you sure i don't need to replace modulesDirectories with something newer?

okay, so babel-core was missing:

npm install --save-dev babel-core

but now its not compiling when i run:

./node_modules/.bin/webpack --config webpack.config.js

it throws an error:

   5 |     render: function() {
   6 |         return (
>  7 |             <h1>
     |             ^
   8 |             Hello, React!
   9 |             </h1>
  10 |         )

the react file (./static/js/index.js):

var React = require('react')
var ReactDOM = require('react-dom')

var Hello = React.createClass ({
    render: function() {
        return (
            <h1>
            Hello, React!
            </h1>
        )
    }
})

ReactDOM.render(<Hello />, document.getElementById('container'))

#7

It definately didn't work if it doesn't understand JSX.

Try to make your resolve object like this:

resolve: {
    modules: [
        "node_modules",
        path.resolve(__dirname, "app")
    ],
    extensions: [".js", ".json", ".jsx", ".css"]
}

#8

here:

path.resolve(__dirname, "app")

what is app? I don't have a directory named app

i have to following in the root of my django app:

thank you for helping me out :slight_smile:


#9

my_app then. I copied it from my project where .js files were in /app folder


#10

but my_app contains only python files:

__init__.py  __pycache__  settings.py  settings.py.back  urls.py  wsgi.py

did i miss something? Do i need to generate a node project in my django project?


#11

I don't think you should. I'd probably read through react/webpack documentation or django + react tutorials. I'm not familiar with django


#12

In my recent project i'm using create-react-app. It creates single dev dependency called "react-scripts" and does all webpack and babel for you behind the scenes. You don't need to setup anything. Once you're ready to deploy you just run npm run build and then your app is compressed and ugilified into a single file. I suggest you read about create-react-app with django setup. Let me know if you succeeded :slight_smile:


#13

i will, thank you

Then i need to figure out how to serve the file with Django, what does npm run build output? A Js or .min.js file? Then i should be good


#14

I hadn't run npm run build yet since i'm not yet deploying. You don't need to run it in developement mode - just when you're about to deploy :). Definately read about create-react-app and you also need to decide whether you're going to go with server-side or client-side rendering. If you go with clien't side then all the react will work on user's browser, and you can use react-router to leave routing also up to user's browser - that's what I'm using right now. Your back-end will be API only :slight_smile: .


#15

i want to do this, Django has DRF (django react framework) which is ideal as API


#16

what do you use as API/backend? NodeJS?


#17

Yes, I'm using NodeJS :slight_smile:


#18

New to Django and even more up to date to ReactJS. I have been investigating AngularJS and ReactJS, however chose ReactJS. It appeared as though it was defeating AngularJS to the extent ubiquity notwithstanding AngularJS having even more a piece of the overall industry, and ReactJS is said to be snappier to pickup.

Regardless of that garbage, I began taking a course on Udemy and after a couple of recordings it appeared to be essential to perceive how well it coordinates with Django. That is the point at which I unavoidably hit a stopping point simply getting it up and running, what sort of documentation is out there with the goal that I am not wasting my time for a few hours and evenings.

There truly isn’t any exhaustive instructional exercises, or pip bundles, I ran over. The few I ran over didn’t work or were dated, pyreact for instance.

One idea I had was simply to treat ReactJS totally partitioned, however keeping into thought the classes and IDs I need the ReactJS segments to render in. After the different ReactJS parts are ordered into a solitary ES5 document, simply import that solitary record into the Django format.

I feel that will rapidly breakdown when I get to rendering from Django models despite the fact that the Django Rest Framework sounds like it is included. Not even sufficiently far to perceive how Redux influences the majority of this.

Anyway, anybody have a reasonable way they are utilizing Django and ReactJS they want to share?

At any rate, the documentation and instructional exercises are ample for AngularJS and Django, so it is enticing to simply go that course to begin with any front-end structure… Not the best reason.


#19

i followed mostly this guide:

http://geezhawk.github.io/using-react-with-django-rest-framework

the only problem i experienced was that the resolve section in webpack.config.js wasn’t working, so i build the config from scratch

inside the root directory of your django app:

npm init -y
npm install --save-dev jquery react react-dom webpack webpack-bundle-tracker babel-loader babel-core babel-preset-es2015 babel-preset-react

my final webpack.config.js:

// webpack.config.js
var path = require('path')
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
module.exports = {
    entry: {
        Bundle: './forum/static/js/index.js',
        Forum: './forum/static/js/forum.js'
    },
    output: {
        path: path.resolve('./forum/static/js'),
        filename: '[name].js'       
    },
    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({ 
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery' 
        })
    ],
    module: {
        loaders: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    }
};

i don’t like the entry points, but i messed up the static directories, now i understand why. But i started again, so not going to fix it

then i used this:

https://webpack.github.io/docs/usage.html

to build my webpack config file