Skip to content

06. Installing React

Lucy Stringer edited this page Feb 23, 2021 · 1 revision

Initializing React in Django backend:

In the main directory of your Django project create a new app called frontend

django-admin startapp frontend

Remember to add this new app into your installed apps in the /pet-tential/settings.py

frontend.apps.FrontendConfig

Next, within this directory create the following folders:

  • src
    • components
  • static
    • css
    • frontend
    • images
  • templates

Next we have to install react and packages:

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 @material-ui/core
npm install @babel/plugin-proposal-class-properties
npm install react-router-dom
npm install @material-ui/icons

create a new file inside frontend called babel.config.json and within that we add:

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

Create a webpack.config.js file Within this file add:

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"),
      },
    }),
  ],
};

NB we might need to change "filename: "[name].js"

Within package.json file We need to replace:

"scripts": {
    "dev": "webpack --mode development --watch",
    "build": "webpack --mode production"
  },

Clone this wiki locally