Serving React from Django
January 14, 2023 |
permanent
Summary #
Serving in
Steps #
- Install ,
npm install --save-dev @babel/core
# install presets and plugins for react
npm install --save-dev @babel/preset-env @babel/preset-react
- Create .babelrc file in the react root dir To use the installed presets and plugins
# automatic is added to avoid react not found error
{
"presets": [
"@babel/preset-env",
["@babel/preset-react", {"runtime": "automatic"}]
]
}
- install, Note: while following the tutorial webpack-bundle-tracker version 1.0.0 worked not the one mentioned the tutorial.
npm install --save-dev webpack webpack-cli webpack-bundle-tracker@1.0.0 babel-loader css-loader style-loader clean-webpack-plugin
a. webpack is… well, Webpack b. webpack-cli allows you to run Webpack commands from the command line c. webpack-bundle-tracker is a plugin that writes some stats about the bundle(s) to a JSON file. d. babel-loader is a loader that tells Webpack to run Babel on the file before adding it to the bundle. e. css-loader and style-loader are loaders that allow you to import .css files into your JavaScript f. clean-webpack-plugin is a plugin that deletes old bundles from Webpack’s output directory every time a new bundle is created.
add webpack.config.js frontend app, ui, is in root of the repo at the same level as that of Django app.
const path = require('path') const BundleTracker = require('webpack-bundle-tracker') const { CleanWebpackPlugin } = require('clean-webpack-plugin') module.exports = { entry: { ui: './src/index.js', }, output: { path: path.resolve('../ksaflyer/app/static/frontend/'), // filename: '[name]-[hash].js', filename: '[name].js', // bundle will be created with ""ui"" name publicPath: 'static/frontend/', // publicPath: "auto" }, plugins: [ new CleanWebpackPlugin(), new BundleTracker({ path: __dirname, filename: '../ksaflyer/ksaflyer/webpack-stats.json', }), ], module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: ['babel-loader'], }, { test: /\.css$/, use: ['style-loader', 'css-loader'], }, ], }, }Add scrips in the package.json
"scripts": { ..., "dev": "webpack --config webpack.config.js --watch --mode development", "build": "webpack --config webpack.config.js --mode production" }Install “django-webpack-loader” and configure
import os
...
INSTALLED_APPS = [
'webpack_loader',
...
]
...
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'frontend/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json')
}
}
- add “index.html” webpack loader
{% extends 'common/base.html' %}
{% load static %}
{% load render_bundle from webpack_loader %}
{% block content %}
<div class="container">
<div id="root"></div>
</div>
{% render_bundle 'ui' %} # ui is input entry name in webpack.config.js
{% endblock content %}
</html>