I was following this tutorial to set up Django to serve templates with webpack-generated bundles. I have set it up just like in the tutorial. However the problem is when i go to localhost:8000 I get Uncaught SyntaxError: Unexpected token < exception when I open the console in chrome devtools. Other html I put in the template file gets rendered except the reactjs bundle. My folder structure is as follows:
.
├── djangoapp
│ ├── db.sqlite3
│ ├── djangoapp
│ │ ├── __init__.py
│ │ ├── settings.py
│ │ ├── urls.py
│ │ └── wsgi.py
│ ├── manage.py
│ ├── reactapp
│ │ └── static
│ │ ├── bundles
│ │ │ └── main-fdf4c969af981093661f.js
│ │ └── js
│ │ └── index.jsx
│ ├── requirements.txt
│ ├── templates
│ │ └── index.html
│ └── webpack-stats.json
├── package.json
├── package-lock.json
└── webpack.config.js
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'webpack_loader'
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates"), ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
}
}
STATIC_URL = 'static/'
webpack.config.js
var path = require("path");
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
module.exports = {
context: __dirname,
entry: './djangoapp/reactapp/static/js/index.jsx',
output: {
path: path.resolve('./djangoapp/reactapp/static/bundles/'),
filename: "[name]-[hash].js",
},
plugins: [
new BundleTracker({filename: './djangoapp/webpack-stats.json'}),
],
module: {
rules: [
{ test: /\.js$/, use: ['babel-loader'], exclude: /node_modules/},
{ test: /\.jsx$/, use: ['babel-loader'], exclude: /node_modules/}
]
},
resolve: {
modules: ['node_modules', 'bower_components'],
extensions: ['.js', '.jsx']
},
};
templates/index.html
{% load render_bundle from webpack_loader %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
<div id="react"></div>
{% render_bundle 'main' %}
</body>
</html>
.babelrc
{
"presets": ["babel-preset-env", "react"]
}
The exception is thrown at the start of line 1 of the main-fdf4c969af981093661f.js file, on the opening tag of <!DOCTYPE html> element. My guess is that the browser expects javascript code, but instead it is given html. Also, I don't understand how does Django know where to look for the bundles since I didn't specify the root (the reactapp directory) of the static/bundles anywhere.