1. The document discusses integrating Webpack into a Django project to bundle static files.
2. It provides an example Django application and shows how to set up basic Webpack configuration to bundle Vue.js and other static files.
3. Additional Webpack features like hot reloading and code splitting are demonstrated to improve the development and production workflows.
2. About Me
Many time PyCon Ireland attendee (many t-shirts! 👕👕), 1st time PyCon
speaker
Working with Python (and JavaScript) for over seven years 🐍
Software engineer at OpenApp, creating bespoke Web applications
Server and client-side Web development
2
@davgibbs
@davgibbs
3. About OpenApp
Founded in 2002, 45 staff employed
Web applications for industries such as Healthcare and Postal. Patient registries,
health data analytics
Always interested in interesting CVs (Software engineers, Project managers, QA
and test automation, etc). hr@openapp.ie
Recent greenfield project, an address cleaning application
Decided on Vue.js and webpack - origin of this talk
3
4. About Talk
Django (without webpack)
Webpack introduction
Integration of webpack into Django
Added webpack extras
4
5. Talk goals
1. Webpack worth learning
The latest JavaScript features can improve your application
2. Straightforward to incorporate into Django
Simple architecture works for local development and production
5
9. Django
A high-level Python Web framework that encourages rapid development and
clean pragmatic design
MTV separation with models-template-views architecture
● Models define what is created in database
● Templates contain presentation logic
● Views contain business logic
Django static (eg js, css, images) stored in static file directories and referenced
in HTML Template code.
9
10. Example application
Small example application:
PyCon Ireland 2019 theme: “Environment”.
Django API provides a random “Environment” related quote.
Result: Request and display quote and corresponding author.
10
11. 11
Models and views for Django API.
HTML template references
frontend files
A frontend directory with static (js,
css, images)
12. Models
Store the quote text and the author
12
from django.db import models
class Quote(models.Model):
text = models.CharField(max_length=1000, help_text="The quote text")
author = models.CharField(max_length=100, help_text="The quote author")
13. Django fixtures
Fixture file environment.json contains a list of famous environment quotes
13
{
"model": "quotes.Quote",
"pk": 1,
"fields": {
"text": "The Earth is what we all have in common.",
"author": "Wendell Berry"
}
},
14. Send request to URL “/random-quote” to get a random Environment quote
Views
14
from django.http import JsonResponse
from django.forms.models import model_to_dict
from .models import Quote
def random_quote(request):
quote = Quote.objects.order_by('?').first()
return JsonResponse(model_to_dict(quote))
20. That is great, my Web application is working.
20
So why do I need this webpack?
21. Missing frontend requirements
● On production, minified JavaScript code with any comments removed
● Unique hash in file names to let browser cache know file updated
● On development, page refresh on code change while retaining state
● Code splitting so that only minimal code downloaded to browser
21
23. Static module bundler for modern JavaScript
Initial release in 2012. Currently version 4.
Pete Hunt spoke at OSCON 2014 on how Instagram use webpack.
Can add/remove functionality as you need it
Enter webpack
23
“Best asset manager is webpack“
~ PyCon 2019 talk by Django co-creator Jacob Kaplan-Moss
24. webpack
webpack.config.js contains all config needed.
Configure webpack for your specific needs: React.js, Vue.js, etc.
Contains information on the mode, input and output along with any plugins or
loaders used.
24
npm install webpack webpack-cli
26. Webpack.config.js - core concepts
1. mode: “development” or “production” enables the built-in optimizations
2. entry: this is the file(s) which is the starting point for webpack
3. output: this configuration is the place where webpack will place the bundles
26
mode: 'production',
entry: { app: './apps/frontend/js/index.js'},
output: { filename: '[name].[hash].bundle.js',
path: __dirname + '/apps/frontend/dist/',
publicPath: '/static/dist/' },
27. Webpack.config.js - core concepts
4. plugins: are used for wide range of tasks such as asset management
5. loaders: allow processing of other types of files. (css, etc)
27
plugins: [new VueLoaderPlugin()],
module: {rules: [
{ test: /.css$/, use: ['style-loader', 'css-loader']},
{ test: /.vue$/, use: 'vue-loader'},
{ test: /.*.(png|jpe?g)$/, use: 'file-loader'}]}
29. Update Vue.js code
Webpack also enables the use of Single File Components (SFCs) in vue.js
Really useful as the project expands to create reusable and isolated components
Create new file App.vue. html, javascript and css for app in one file. File index.js
is entry point to App.vue.
29
30. 30
NPM scripts: build command
In package.json “scripts” section add a line for “build” command:
scripts: {"build": "webpack"}
31. Missing frontend requirements
● On production, minified JavaScript code with any comments removed
● Unique hash in file names to let browser cache know file updated
31
33. Library to transparently use webpack with django
Metadata file, produced by webpack plugin, tells Django where the generated
files are located.
33
Enter “django-webpack-loader”
“One of the core principles of django-webpack-loader is to not manage webpack
itself in order to give you the flexibility to run webpack the way you want.“
~ django-webpack-loader documentation
34. 34
Update JavaScript side
const BundleTracker = require('webpack-bundle-tracker');]
plugins: [
<other plugins>...
new BundleTracker({filename: './apps/webpack-stats.json'}),
]
1. npm install webpack-bundle-tracker
2. Add BundleTracker to webpack.config.js which will write to file on build
35. 1. pip install django-webpack-loader
2. Update Django’s settings.py
a. Add “webpack_loader” to INSTALLED_APPS
b. Add in a section WEBPACK_LOADER:
3. Use “render_bundle” template tag rather then “static” in templates. This
links to the files generated in dist/ directory
35
Update Django side
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'dist/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json')}}
36. Integrated!
npm run build is run first to create the bundles
● Bundles in “dist” directory. webpack-stats.json contains the filenames
python manager.py runserver follows to run Django
● Django template will include the bundled files from webpack
36
38. Missing frontend requirements
● On production, minified JavaScript code with any comments removed -> Set
the mode to ‘production’
● Unique hash in file names to let browser cache know file updated -> Include
unique hash in each filename
● On development, page refresh on code change while retaining state
● Code splitting so that only minimal code downloaded to browser
38
40. Extra webpack configuration
40
The following additional configurations can be added as needed:
Eslint, Babel, clean old bundles plugin, bundle analyzer plugin, …
Chosen extras:
1. Webpack-dev-server: Hot-reload for local development
2. Code splitting: define multiple entry points to avoid downloading the same
code to the browser twice
41. Webpack-dev-server
On a code change, re-run build and update Browser display for quicker
development.
Webpack-dev-server runs in one terminal tab and Django development server in
another tab.
41
webpack-dev-server
Save to File
system
Watch for
changes
Update
display
Browser
42. Webpack-dev-server
Hot reload to refresh page the part of the page that has changed.
npm install webpack-dev-server webpack-merge
Add a 2nd entry to the “scripts” section of package.json:
42
scripts: {"build": "webpack"
"start": "webpack-dev-server --config webpack.dev.js"}
43. Webpack-dev-server
43
Add new config webpack.dev.js for development specific config
const merge = require('webpack-merge');
const common = require('./webpack.config.js');
module.exports = merge(common, {
mode: 'development',
output: {publicPath: 'http://localhost:3000/static/dist/'},
devServer: {
port: 3000,
hot: true,
headers: {'Access-Control-Allow-Origin': '*'}}
});
44. Code Splitting
Powerful webpack feature to split code into various bundles which can then be
loaded on demand or in parallel to help improve page load time.
44
45. Code Splitting
Prevent Duplication: Split out “vendor” code so when a new entry point is added,
no need for browser to re-download vendor (Vue.js, bootstrap).
Separate “render_bundle” call in HTML template for “vendor” bundle
45
optimization: {
splitChunks: {
cacheGroups: { commons: {
test: /[/]node_modules[/]/,
chunks: 'initial',
name: 'vendor'}}}},
46. ● On production, minified JavaScript code with any comments removed -> Set
the mode to ‘production’
● Unique hash in file names to let browser cache know file updated -> Include
hash in each filename
● On development, page refresh on code change while retaining state -> add
webpack-dev-server with configuration to watch source files
● Code splitting so that only minimal code downloaded to browser -> make
use of optimisation in webpack to split files
Missing frontend requirements
46
48. Talk Summary
Webpack is a tool for modern JavaScript development, handles different file
types of static files to produce bundles.
Example application which uses webpack to bundle static files and incorporated
into Django with django-webpack-loader.
Once basic webpack configuration is in place, it is easy to add functionality as
needed.
Tried-and-tested way to webpack your Django!
48