Skip to content

Instantly share code, notes, and snippets.

@eloc0n
Last active March 25, 2021 13:02
Show Gist options
  • Save eloc0n/85d9e47371e9a89f5ca478e881bd9ac6 to your computer and use it in GitHub Desktop.
Save eloc0n/85d9e47371e9a89f5ca478e881bd9ac6 to your computer and use it in GitHub Desktop.
React Integration Using Webpack & Babel

Create frontend app

django-admin startapp frontend
cd frontend

Make sure to add it also into settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'api.apps.ApiConfig',
    'rest_framework',
    'frontend.apps.FrontendConfig'
]

Frontend app flow

Create new folders called templates, static, src, etc...

Inside frontend

frontend
├── static
│    ├── css
│    ├── frontend
│    └── images
├── src
│    └── components
│    └── index.js
└── templates

Webpack & Babel setup for React

Make sure you have in your system npm and nodejs installed. Otherwise skip and move on NPM Setup Commands

sudo apt install nodejs
node -v
sudo apt install npm
npm -v

NPM Setup Commands

npm init -y
npm i webpack webpack-cli --save-dev
npm i @babel/core babel-loader @babel/preset-env @babel/preset-react --save-dev
npm i react react-dom --save-dev
npm install @babel/plugin-proposal-class-properties
npm install react-router-dom

In frontend app create babel.config.json and paste in:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "10"
        }
      }
    ],
    "@babel/preset-react"
  ],
  "plugins": ["@babel/plugin-proposal-class-properties"]
}

Do the same for package.json

{
  "name": "frontend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack --mode development --watch",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.12.3",
    "@babel/preset-env": "^7.12.1",
    "@babel/preset-react": "^7.12.5",
    "babel-loader": "^8.1.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "webpack": "^5.4.0",
    "webpack-cli": "^4.2.0"
  },
  "dependencies": {
    "@babel/plugin-proposal-class-properties": "^7.12.1",
    "react-router-dom": "^5.2.0"
  }
}

And same for webpack.config.js

const path = require("path");
const webpack = require("webpack");

module.exports = {
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "./static/frontend"),
    filename: "[name].js",
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
    ],
  },
  optimization: {
    minimize: true,
  },
  plugins: [
    new webpack.DefinePlugin({
      "process.env": {
        // This has effect on the react lib size
        NODE_ENV: JSON.stringify("production"),
      },
    }),
  ],
};

Inside templates/frontend create a new index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>App name</title>
    {% load static %}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
    />
    <link rel="stylesheet" type="text/css" href="{% static "css/index.css" %}"
    />
  </head>
  <body>
    <div id="main">
      <div id="app"></div>
    </div>

    <script src="{% static "frontend/main.js" %}"></script>
  </body>
</html>

Next go to views.py

from django.shortcuts import render

# Create your views here.


def index(request, *args, **kwargs):
    return render(request, 'frontend/index.html')

We need to configure the main Project urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('api.urls')),
    path('', include('frontend.urls')) <----
]

Same goes for the frontend app, go to frontend/urls.py and paste in:

from django.urls import path
from .views import index

urlpatterns = [
    path('', index),
]

We are ready to create our first component App.js. Go inside frontend/src/components

import React, { Component } from "react";
import { render } from "react-dom";
import HomePage from "./HomePage";

export default class App extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <HomePage />
      </div>
    );
  }
}

const appDiv = document.getElementById("app");
render(<App />, appDiv);

And dont forget to import our components inside the index.js

import App from "./components/App";

Time to see if it works

python manage.py run server

and

npm run dev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment