1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
|
%global _empty_manifest_terminate_build 0
Name: python-django-webpack-loader
Version: 1.8.1
Release: 1
Summary: Transparently use webpack with django
License: MIT License
URL: https://github.com/django-webpack/django-webpack-loader
Source0: https://mirrors.nju.edu.cn/pypi/web/packages/aa/8d/3a7d689e56ad739a3234af47d2dd2bc22172d263233712e3b39c8246615d/django-webpack-loader-1.8.1.tar.gz
BuildArch: noarch
%description
# django-webpack-loader
[](https://circleci.com/gh/django-webpack/django-webpack-loader/tree/master)
[](https://coveralls.io/github/django-webpack/django-webpack-loader?branch=master)


Use webpack to generate your static bundles without django's staticfiles or opaque wrappers.
Django webpack loader consumes the output generated by [webpack-bundle-tracker](https://github.com/owais/webpack-bundle-tracker) and lets you use the generated bundles in django.
A [changelog](CHANGELOG.md) is also available.
## Compatibility
Test cases cover Django>=2.0 on Python>=3.5. 100% code coverage is the target so we can be sure everything works anytime. It should probably work on older version of django as well but the package does not ship any test cases for them.
## Install
```bash
npm install --save-dev webpack-bundle-tracker
pip install django-webpack-loader
```
## Configuration
### Configuring `webpack-bundle-tracker`
Before configuring `django-webpack-loader`, let's first configure what's necessary on `webpack-bundle-tracker` side. Update your Webpack configuration file (it's usually on `webpack.config.js` in the project root). Make sure your file looks like this (adapt to your needs):
```javascript
const path = require('path');
const webpack = require('webpack');
const BundleTracker = require('webpack-bundle-tracker');
module.exports = {
context: __dirname,
entry: './assets/js/index',
output: {
path: path.resolve('./assets/webpack_bundles/'),
filename: "[name]-[hash].js"
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'})
],
}
```
The configuration above expects the `index.js` (the app entrypoint file) to live inside the `/assets/js/` directory (this guide going forward will assume that all front-end related files are placed inside the `/assets/` directory, with the different kinds of files arranged within its subdirectories).
The generated compiled files will be placed inside the `/assets/webpack_bundles/` directory and the file with the information regarding the bundles and assets (`webpack-stats.json`) will be stored in the project root.
### Compiling the front-end assets
You must generate the front-end bundle using `webpack-bundle-tracker` before using `django-webpack-loader`. You can compile the assets and generate the bundles by running:
```bash
npx webpack --config webpack.config.js --watch
```
This will also generate the stats file. You can also refer to how `django-react-boilerplate` configure the [package.json](https://github.com/vintasoftware/django-react-boilerplate/blob/master/package.json) scripts for different situations.
> ⚠️ Hot reload is available through a specific config. Check [this section](#hot-reload).
> ⚠️ This is the recommended usage for the development environment. For **usage in production**, please refer to [this section](#usage-in-production)
### Configuring the settings file
First of all, add `webpack_loader` to `INSTALLED_APPS`.
```python
INSTALLED_APPS = (
...
'webpack_loader',
...
)
```
Below is the recommended setup for the Django settings file when using `django-webpack-loader`.
```python
WEBPACK_LOADER = {
'DEFAULT': {
'CACHE': not DEBUG,
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
'POLL_INTERVAL': 0.1,
'IGNORE': [r'.+\.hot-update.js', r'.+\.map'],
}
}
```
For that setup, we're using the `DEBUG` variable provided by Django. Since in a production environment (`DEBUG = False`) the assets files won't constantly change, we can safely cache the results (`CACHE=True`) and optimize our flow, as `django-webpack-loader` will read the stats file only once and store the assets files paths in memory. From that point onwards, it will use these stored paths as the source of truth. If `CACHE=False`, we'll always read the stats file to get the assets paths.
> ⚠️ If `CACHE=True`, any changes made in the assets files will only be read when the web workers are restarted.
During development, when the stats file changes a lot, we want to always poll for its updated version (in our case, we'll fetch it every 0.1s, as defined on `POLL_INTERVAL`).
> ⚠️ In production (`DEBUG=False`), we'll only fetch the stats file once, so `POLL_INTERVAL` is ignored.
While `CACHE` isn't directly related to `POLL_INTERVAL`, it's interesting to keep `CACHE` binded to the `DEBUG` logic value (in this case, the negation of the logic value) in order to only cache the assets in production, as we'd not continuously poll the stats file in that environment.
The `STATS_FILE` parameter represents the output file produced by `webpack-bundle-tracker`. Since in the Webpack configuration file we've named it `webpack-stats.json` and stored it on the project root, we must replicate that setting on the back-end side.
`IGNORE` is a list of regular expressions. If a file generated by Webpack matches one of the expressions, the file will not be included in the template.
### Extra settings
- `TIMEOUT` is the number of seconds webpack_loader should wait for webpack to finish compiling before raising an exception. `0`, `None` or leaving the value out of settings disables timeouts
- `INTEGRITY` is flag enabling [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) on rendered `<script>` and `<link>` tags. Integrity hash is get from stats file and configuration on side of `BundleTracker`, where configuration option `integrity: true` is required.
- `LOADER_CLASS` is the fully qualified name of a python class as a string that holds the custom webpack loader. This is where behavior can be customized as to how the stats file is loaded. Examples include loading the stats file from a database, cache, external url, etc. For convenience, `webpack_loader.loader.WebpackLoader` can be extended. The `load_assets` method is likely where custom behavior will be added. This should return the stats file as an object.
- `SKIP_COMMON_CHUNKS` is a flag which prevents already generated chunks from being included again in the same page. This should only happen if you use more than one entrypoint per Django template (multiple `render_bundle` calls). By enabling this, you can get the same default behavior of the [HtmlWebpackPlugin](https://webpack.js.org/plugins/html-webpack-plugin/). The same caveats apply as when using `skip_common_chunks` on `render_bundle`, see that section below for more details.
Here's a simple example of loading from an external url:
```py
import requests
from webpack_loader.loader import WebpackLoader
class ExternalWebpackLoader(WebpackLoader):
def load_assets(self):
url = self.config['STATS_URL']
return requests.get(url).json()
```
## Rendering
In order to render the front-end code into the Django templates, we use the `render_bundle` template tag.
Its behavior is to accept a string with the name of an entrypoint from the stats file (in our case, we're using `main`, which is [the default](https://webpack.js.org/concepts/entry-points/#single-entry-shorthand-syntax)) and it'll proceed to include all files under that entrypoint. You can read more about the entrypoints concept [here](https://webpack.js.org/concepts/entry-points/).
> ⚠️ You can also check an example on how to use multiple `entry` values [here](https://github.com/django-webpack/django-webpack-loader/tree/master/examples/code-splitting).
Below is the basic usage for `render_bundle` within a template:
```HTML+Django
{% load render_bundle from webpack_loader %}
{% render_bundle 'main' %}
```
That will render the proper `<script>` and `<link>` tags needed in your template.
## Running in development
For `django-webpack-loader` to work, you must run the webpack pipeline. Please refer to [this section](#compiling-the-front-end-assets).
In summary, you should do the following:
```bash
# in one shell
npx webpack --config webpack.config.js --watch
# in another shell
python manage.py runserver
```
> ⚠️ You can also check [this example](https://github.com/django-webpack/django-webpack-loader/tree/master/examples/simple) on how to run a project with `django-webpack-loader` and `webpack-bundle-track`.
## Usage in production
We recommend that you keep your local bundles and the stats file outside the version control, having a production pipeline that will compile and collect the assets during the deployment phase.
You must add `STATICFILES_DIRS` to your settings file, pointing to the directory where the static files are located. This will let `collectstatic` know where it should look at:
```python
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)
```
Below are the commands that should be run to compile and collect the static files (please note this may change from platform to platform):
```
npm run build
python manage.py collectstatic --noinput
```
First we build the assets and, since we have `webpack-bundle-tracker` in our front-end building pipeline, the stats file will be populated. Then, we manually run collecstatic to collect the compiled assets.
> ⚠️ Heroku is one platform that automatically runs collectstatic for you, so you need to set `DISABLE_COLLECTSTATIC=1` environment var. Instead, you must manually run collectstatic after running webpack. In Heroku, this is achieved with a `post_compile` hook. You can see an example on how to implement this flow on [django-react-boilerplate](https://github.com/vintasoftware/django-react-boilerplate/tree/master/bin).
However, production usage for this package is **fairly flexible**. Other approaches may include keeping the production bundles in the version control and take that responsibility from the automatic pipeline. However, you must remember to always build the frontend and generate the bundle before pushing to remote.
## Usage in tests
To run tests where `render_bundle` shows up, since we don't have `webpack-bundle-tracker` at that point to generate the stats file, the calls to render the bundle will fail. The solution is to use the `FakeWebpackLoader` in your test settings:
```python
WEBPACK_LOADER['DEFAULT']['LOADER_CLASS'] = 'webpack_loader.loader.FakeWebpackLoader'
```
## Advanced Usage
### Rendering by file extension
`render_bundle` also takes a second argument which can be a file extension to match. This is useful when you want to render different types for files in separately. For example, to render CSS in head and JS at bottom we can do something like this,
```HTML+Django
{% load render_bundle from webpack_loader %}
<html>
<head>
{% render_bundle 'main' 'css' %}
</head>
<body>
....
{% render_bundle 'main' 'js' %}
</body>
</head>
```
### Using preload
The `is_preload=True` option in the `render_bundle` template tag can be used to add `rel="preload"` link tags.
```HTML+Django
{% load render_bundle from webpack_loader %}
<html>
<head>
{% render_bundle 'main' 'css' is_preload=True %}
{% render_bundle 'main' 'js' is_preload=True %}
{% render_bundle 'main' 'css' %}
</head>
<body>
{% render_bundle 'main' 'js' %}
</body>
</html>
```
### Accessing other webpack assets
`webpack_static` template tag provides facilities to load static assets managed by webpack in Django templates. It is like Django's built in `static` tag but for webpack assets instead.
In the below example, `logo.png` can be any static asset shipped with any npm package.
```HTML+Django
{% load webpack_static from webpack_loader %}
<!-- render full public path of logo.png -->
<img src="{% webpack_static 'logo.png' %}"/>
```
The public path is based on `webpack.config.js` [output.publicPath](https://webpack.js.org/configuration/output/#output-publicpath).
Please note that this approach will use the original asset file, and not a post-processed one from the Webpack pipeline, in case that file had gone through such flow (i.e.: You've imported an image on the React side and used it there, the file used within the React components will probably have a hash string on its name, etc. This processed file will be different than the one you'll grab with `webpack_static`).
### Use `skip_common_chunks` on `render_bundle`
You can use the parameter `skip_common_chunks=True` or `skip_common_chunks=False` to override the global `SKIP_COMMON_CHUNKS` setting for a specific bundle.
In order for this option to work, `django-webpack-loader` requires the `request` object to be in the context, to be able to keep track of the generated chunks.
The `request` object is passed by default via the `django.template.context_processors.request` middleware with using the Django built-in templating system, and also with using Jinja2.
If you don't have `request` in the context for some reason (e.g. using `Template.render` or `render_to_string` directly without passing the request), you'll get warnings on the console and the common chunks will remain duplicated.
### Appending file extensions
The `suffix` option can be used to append a string at the end of the file URL. For instance, it can be used if your webpack configuration emits compressed `.gz` files.
qwe
```HTML+Django
{% load render_bundle from webpack_loader %}
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
{% render_bundle 'main' 'css' %}
</head>
<body>
{% render_bundle 'main' 'js' suffix='.gz' %}
</body>
</html>
```
### Multiple Webpack configurations
Version 1.0 and up of `django-webpack-loader` also supports multiple Webpack configurations. The following configuration defines 2 Webpack stats files in settings and uses the `config` argument in the template tags to influence which stats file to load the bundles from.
```python
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
},
'DASHBOARD': {
'BUNDLE_DIR_NAME': 'dashboard_bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats-dashboard.json'),
}
}
```
```HTML+Django
{% load render_bundle from webpack_loader %}
<html>
<body>
....
{% render_bundle 'main' 'js' 'DEFAULT' %}
{% render_bundle 'main' 'js' 'DASHBOARD' %}
<!-- or render all files from a bundle -->
{% render_bundle 'main' config='DASHBOARD' %}
<!-- the following tags do the same thing -->
{% render_bundle 'main' 'css' 'DASHBOARD' %}
{% render_bundle 'main' extension='css' config='DASHBOARD' %}
{% render_bundle 'main' config='DASHBOARD' extension='css' %}
<!-- add some extra attributes to the tag -->
{% render_bundle 'main' 'js' 'DEFAULT' attrs='async charset="UTF-8"'%}
</body>
</head>
```
### File URLs instead of html tags
If you need the URL to an asset without the HTML tags, the `get_files` template tag can be used. A common use case is specifying the URL to a custom css file for a Javascript plugin.
`get_files` works exactly like `render_bundle` except it returns a list of matching files and lets you assign the list to a custom template variable.
Each object in the returned list has 2 properties:
1. `name`, which is the name of a chunk from the stats file;
2. `url`, which can be:
1. The `publicPath` if the asset has one;
2. The `path` to the asset in the static files storage, if the asset doesn't have a `publicPath`.
For example:
```HTML+Django
{% load get_files from webpack_loader %}
{% get_files 'editor' 'css' as editor_css_files %}
CKEDITOR.config.contentsCss = '{{ editor_css_files.0.url }}';
<!-- or list down name and url for every file -->
<ul>
{% for css_file in editor_css_files %}
<li>{{ css_file.name }} : {{ css_file.url }}</li>
{% endfor %}
</ul>
```
### Code splitting
In case you wish to use [code-splitting](https://webpack.js.org/guides/code-splitting/), follow the recipe below on the Javascript side.
Create your entrypoint file and add elements to the DOM, while leveraging the lazy imports.
```js
// src/principal.js
function getComponent() {
return import(/* webpackChunkName: "lodash" */ 'lodash').then(({ default: _ }) => {
const element = document.createElement('div');
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}).catch(error => 'An error occurred while loading the component');
}
getComponent().then((component) => {
document.body.appendChild(component);
})
```
On your configuration file, do the following:
```js
// webpack.config.js
module.exports = {
context: __dirname,
entry: {
principal: './src/principal',
},
output: {
path: path.resolve('./dist/'),
// publicPath should match your STATIC_URL config.
// This is required otherwise webpack will try to fetch
// our chunk generated by the dynamic import from "/" instead of "/dist/".
publicPath: '/dist/',
chunkFilename: '[name].bundle.js',
filename: "[name]-[hash].js"
},
plugins: [
new BundleTracker({ filename: './webpack-stats.json' })
]
}
```
If you're using Webpack 5 instead of 4, do the following:
- Change `filename: "[name]-[hash].js"` to `filename: "[name]-[fullhash].js"`;
- Remove `/* webpackChunkName: "lodash" */`, which is not needed anymore.
On your template, render the bundle as usual:
```HTML+Django
<!-- index.html -->
{% load render_bundle from webpack_loader %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My test page</title>
</head>
<body>
<p>This is my page</p>
{% render_bundle 'principal' 'js' %}
</body>
</html>
```
### Hot reload
In case you wish to enable hot reload for your project using `django-webpack-loader` and `webpack-bundle-tracker`, please check out [this example](https://github.com/django-webpack/django-webpack-loader/tree/master/examples/hot-reload), in particular how [server.js](https://github.com/django-webpack/django-webpack-loader/blob/master/examples/hot-reload/server.js) and [webpack.config.js](https://github.com/django-webpack/django-webpack-loader/blob/master/examples/hot-reload/webpack.config.js) are configured.
### Jinja2 Configuration
If you need to output your assets in a jinja template, we provide a Jinja2 extension that's compatible with [django-jinja](https://github.com/niwinz/django-jinja).
To install the extension, add it to the `TEMPLATES` configuration in the `["OPTIONS"]["extension"]` list.
```python
from django_jinja.builtins import DEFAULT_EXTENSIONS
TEMPLATES = [
{
"BACKEND": "django_jinja.backend.Jinja2",
"OPTIONS": {
"extensions": DEFAULT_EXTENSIONS + [
"webpack_loader.contrib.jinja2ext.WebpackExtension",
],
}
}
]
```
Then in your base jinja template, do:
```HTML
{{ render_bundle('main') }}
```
## Migrating from version < 1.0.0
In order to use `django-webpack-loader>=1.0.0`, you must ensure that `webpack-bundle-tracker@1.0.0` is being used on the JavaScript side. It's recommended that you always keep at least minor version parity across both packages, for full compatibility.
This is necessary because the formatting of `webpack-stats.json` that `webpack-bundle-tracker` outputs has changed starting at version `1.0.0-alpha.1`. Starting at `django-webpack-loader==1.0.0`, this is the only formatting accepted here, meaning that other versions of that package don't output compatible files anymore, thereby breaking compatibility with older `webpack-bundle-tracker` releases.
## Commercial Support
[](https://www.vinta.com.br/)
This project is maintained by [Vinta Software](https://www.vinta.com.br/) and is used in products of Vinta's clients. We are always looking for exciting work, so if you need any commercial support, feel free to get in touch: contact@vinta.com.br
%package -n python3-django-webpack-loader
Summary: Transparently use webpack with django
Provides: python-django-webpack-loader
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-django-webpack-loader
# django-webpack-loader
[](https://circleci.com/gh/django-webpack/django-webpack-loader/tree/master)
[](https://coveralls.io/github/django-webpack/django-webpack-loader?branch=master)


Use webpack to generate your static bundles without django's staticfiles or opaque wrappers.
Django webpack loader consumes the output generated by [webpack-bundle-tracker](https://github.com/owais/webpack-bundle-tracker) and lets you use the generated bundles in django.
A [changelog](CHANGELOG.md) is also available.
## Compatibility
Test cases cover Django>=2.0 on Python>=3.5. 100% code coverage is the target so we can be sure everything works anytime. It should probably work on older version of django as well but the package does not ship any test cases for them.
## Install
```bash
npm install --save-dev webpack-bundle-tracker
pip install django-webpack-loader
```
## Configuration
### Configuring `webpack-bundle-tracker`
Before configuring `django-webpack-loader`, let's first configure what's necessary on `webpack-bundle-tracker` side. Update your Webpack configuration file (it's usually on `webpack.config.js` in the project root). Make sure your file looks like this (adapt to your needs):
```javascript
const path = require('path');
const webpack = require('webpack');
const BundleTracker = require('webpack-bundle-tracker');
module.exports = {
context: __dirname,
entry: './assets/js/index',
output: {
path: path.resolve('./assets/webpack_bundles/'),
filename: "[name]-[hash].js"
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'})
],
}
```
The configuration above expects the `index.js` (the app entrypoint file) to live inside the `/assets/js/` directory (this guide going forward will assume that all front-end related files are placed inside the `/assets/` directory, with the different kinds of files arranged within its subdirectories).
The generated compiled files will be placed inside the `/assets/webpack_bundles/` directory and the file with the information regarding the bundles and assets (`webpack-stats.json`) will be stored in the project root.
### Compiling the front-end assets
You must generate the front-end bundle using `webpack-bundle-tracker` before using `django-webpack-loader`. You can compile the assets and generate the bundles by running:
```bash
npx webpack --config webpack.config.js --watch
```
This will also generate the stats file. You can also refer to how `django-react-boilerplate` configure the [package.json](https://github.com/vintasoftware/django-react-boilerplate/blob/master/package.json) scripts for different situations.
> ⚠️ Hot reload is available through a specific config. Check [this section](#hot-reload).
> ⚠️ This is the recommended usage for the development environment. For **usage in production**, please refer to [this section](#usage-in-production)
### Configuring the settings file
First of all, add `webpack_loader` to `INSTALLED_APPS`.
```python
INSTALLED_APPS = (
...
'webpack_loader',
...
)
```
Below is the recommended setup for the Django settings file when using `django-webpack-loader`.
```python
WEBPACK_LOADER = {
'DEFAULT': {
'CACHE': not DEBUG,
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
'POLL_INTERVAL': 0.1,
'IGNORE': [r'.+\.hot-update.js', r'.+\.map'],
}
}
```
For that setup, we're using the `DEBUG` variable provided by Django. Since in a production environment (`DEBUG = False`) the assets files won't constantly change, we can safely cache the results (`CACHE=True`) and optimize our flow, as `django-webpack-loader` will read the stats file only once and store the assets files paths in memory. From that point onwards, it will use these stored paths as the source of truth. If `CACHE=False`, we'll always read the stats file to get the assets paths.
> ⚠️ If `CACHE=True`, any changes made in the assets files will only be read when the web workers are restarted.
During development, when the stats file changes a lot, we want to always poll for its updated version (in our case, we'll fetch it every 0.1s, as defined on `POLL_INTERVAL`).
> ⚠️ In production (`DEBUG=False`), we'll only fetch the stats file once, so `POLL_INTERVAL` is ignored.
While `CACHE` isn't directly related to `POLL_INTERVAL`, it's interesting to keep `CACHE` binded to the `DEBUG` logic value (in this case, the negation of the logic value) in order to only cache the assets in production, as we'd not continuously poll the stats file in that environment.
The `STATS_FILE` parameter represents the output file produced by `webpack-bundle-tracker`. Since in the Webpack configuration file we've named it `webpack-stats.json` and stored it on the project root, we must replicate that setting on the back-end side.
`IGNORE` is a list of regular expressions. If a file generated by Webpack matches one of the expressions, the file will not be included in the template.
### Extra settings
- `TIMEOUT` is the number of seconds webpack_loader should wait for webpack to finish compiling before raising an exception. `0`, `None` or leaving the value out of settings disables timeouts
- `INTEGRITY` is flag enabling [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) on rendered `<script>` and `<link>` tags. Integrity hash is get from stats file and configuration on side of `BundleTracker`, where configuration option `integrity: true` is required.
- `LOADER_CLASS` is the fully qualified name of a python class as a string that holds the custom webpack loader. This is where behavior can be customized as to how the stats file is loaded. Examples include loading the stats file from a database, cache, external url, etc. For convenience, `webpack_loader.loader.WebpackLoader` can be extended. The `load_assets` method is likely where custom behavior will be added. This should return the stats file as an object.
- `SKIP_COMMON_CHUNKS` is a flag which prevents already generated chunks from being included again in the same page. This should only happen if you use more than one entrypoint per Django template (multiple `render_bundle` calls). By enabling this, you can get the same default behavior of the [HtmlWebpackPlugin](https://webpack.js.org/plugins/html-webpack-plugin/). The same caveats apply as when using `skip_common_chunks` on `render_bundle`, see that section below for more details.
Here's a simple example of loading from an external url:
```py
import requests
from webpack_loader.loader import WebpackLoader
class ExternalWebpackLoader(WebpackLoader):
def load_assets(self):
url = self.config['STATS_URL']
return requests.get(url).json()
```
## Rendering
In order to render the front-end code into the Django templates, we use the `render_bundle` template tag.
Its behavior is to accept a string with the name of an entrypoint from the stats file (in our case, we're using `main`, which is [the default](https://webpack.js.org/concepts/entry-points/#single-entry-shorthand-syntax)) and it'll proceed to include all files under that entrypoint. You can read more about the entrypoints concept [here](https://webpack.js.org/concepts/entry-points/).
> ⚠️ You can also check an example on how to use multiple `entry` values [here](https://github.com/django-webpack/django-webpack-loader/tree/master/examples/code-splitting).
Below is the basic usage for `render_bundle` within a template:
```HTML+Django
{% load render_bundle from webpack_loader %}
{% render_bundle 'main' %}
```
That will render the proper `<script>` and `<link>` tags needed in your template.
## Running in development
For `django-webpack-loader` to work, you must run the webpack pipeline. Please refer to [this section](#compiling-the-front-end-assets).
In summary, you should do the following:
```bash
# in one shell
npx webpack --config webpack.config.js --watch
# in another shell
python manage.py runserver
```
> ⚠️ You can also check [this example](https://github.com/django-webpack/django-webpack-loader/tree/master/examples/simple) on how to run a project with `django-webpack-loader` and `webpack-bundle-track`.
## Usage in production
We recommend that you keep your local bundles and the stats file outside the version control, having a production pipeline that will compile and collect the assets during the deployment phase.
You must add `STATICFILES_DIRS` to your settings file, pointing to the directory where the static files are located. This will let `collectstatic` know where it should look at:
```python
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)
```
Below are the commands that should be run to compile and collect the static files (please note this may change from platform to platform):
```
npm run build
python manage.py collectstatic --noinput
```
First we build the assets and, since we have `webpack-bundle-tracker` in our front-end building pipeline, the stats file will be populated. Then, we manually run collecstatic to collect the compiled assets.
> ⚠️ Heroku is one platform that automatically runs collectstatic for you, so you need to set `DISABLE_COLLECTSTATIC=1` environment var. Instead, you must manually run collectstatic after running webpack. In Heroku, this is achieved with a `post_compile` hook. You can see an example on how to implement this flow on [django-react-boilerplate](https://github.com/vintasoftware/django-react-boilerplate/tree/master/bin).
However, production usage for this package is **fairly flexible**. Other approaches may include keeping the production bundles in the version control and take that responsibility from the automatic pipeline. However, you must remember to always build the frontend and generate the bundle before pushing to remote.
## Usage in tests
To run tests where `render_bundle` shows up, since we don't have `webpack-bundle-tracker` at that point to generate the stats file, the calls to render the bundle will fail. The solution is to use the `FakeWebpackLoader` in your test settings:
```python
WEBPACK_LOADER['DEFAULT']['LOADER_CLASS'] = 'webpack_loader.loader.FakeWebpackLoader'
```
## Advanced Usage
### Rendering by file extension
`render_bundle` also takes a second argument which can be a file extension to match. This is useful when you want to render different types for files in separately. For example, to render CSS in head and JS at bottom we can do something like this,
```HTML+Django
{% load render_bundle from webpack_loader %}
<html>
<head>
{% render_bundle 'main' 'css' %}
</head>
<body>
....
{% render_bundle 'main' 'js' %}
</body>
</head>
```
### Using preload
The `is_preload=True` option in the `render_bundle` template tag can be used to add `rel="preload"` link tags.
```HTML+Django
{% load render_bundle from webpack_loader %}
<html>
<head>
{% render_bundle 'main' 'css' is_preload=True %}
{% render_bundle 'main' 'js' is_preload=True %}
{% render_bundle 'main' 'css' %}
</head>
<body>
{% render_bundle 'main' 'js' %}
</body>
</html>
```
### Accessing other webpack assets
`webpack_static` template tag provides facilities to load static assets managed by webpack in Django templates. It is like Django's built in `static` tag but for webpack assets instead.
In the below example, `logo.png` can be any static asset shipped with any npm package.
```HTML+Django
{% load webpack_static from webpack_loader %}
<!-- render full public path of logo.png -->
<img src="{% webpack_static 'logo.png' %}"/>
```
The public path is based on `webpack.config.js` [output.publicPath](https://webpack.js.org/configuration/output/#output-publicpath).
Please note that this approach will use the original asset file, and not a post-processed one from the Webpack pipeline, in case that file had gone through such flow (i.e.: You've imported an image on the React side and used it there, the file used within the React components will probably have a hash string on its name, etc. This processed file will be different than the one you'll grab with `webpack_static`).
### Use `skip_common_chunks` on `render_bundle`
You can use the parameter `skip_common_chunks=True` or `skip_common_chunks=False` to override the global `SKIP_COMMON_CHUNKS` setting for a specific bundle.
In order for this option to work, `django-webpack-loader` requires the `request` object to be in the context, to be able to keep track of the generated chunks.
The `request` object is passed by default via the `django.template.context_processors.request` middleware with using the Django built-in templating system, and also with using Jinja2.
If you don't have `request` in the context for some reason (e.g. using `Template.render` or `render_to_string` directly without passing the request), you'll get warnings on the console and the common chunks will remain duplicated.
### Appending file extensions
The `suffix` option can be used to append a string at the end of the file URL. For instance, it can be used if your webpack configuration emits compressed `.gz` files.
qwe
```HTML+Django
{% load render_bundle from webpack_loader %}
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
{% render_bundle 'main' 'css' %}
</head>
<body>
{% render_bundle 'main' 'js' suffix='.gz' %}
</body>
</html>
```
### Multiple Webpack configurations
Version 1.0 and up of `django-webpack-loader` also supports multiple Webpack configurations. The following configuration defines 2 Webpack stats files in settings and uses the `config` argument in the template tags to influence which stats file to load the bundles from.
```python
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
},
'DASHBOARD': {
'BUNDLE_DIR_NAME': 'dashboard_bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats-dashboard.json'),
}
}
```
```HTML+Django
{% load render_bundle from webpack_loader %}
<html>
<body>
....
{% render_bundle 'main' 'js' 'DEFAULT' %}
{% render_bundle 'main' 'js' 'DASHBOARD' %}
<!-- or render all files from a bundle -->
{% render_bundle 'main' config='DASHBOARD' %}
<!-- the following tags do the same thing -->
{% render_bundle 'main' 'css' 'DASHBOARD' %}
{% render_bundle 'main' extension='css' config='DASHBOARD' %}
{% render_bundle 'main' config='DASHBOARD' extension='css' %}
<!-- add some extra attributes to the tag -->
{% render_bundle 'main' 'js' 'DEFAULT' attrs='async charset="UTF-8"'%}
</body>
</head>
```
### File URLs instead of html tags
If you need the URL to an asset without the HTML tags, the `get_files` template tag can be used. A common use case is specifying the URL to a custom css file for a Javascript plugin.
`get_files` works exactly like `render_bundle` except it returns a list of matching files and lets you assign the list to a custom template variable.
Each object in the returned list has 2 properties:
1. `name`, which is the name of a chunk from the stats file;
2. `url`, which can be:
1. The `publicPath` if the asset has one;
2. The `path` to the asset in the static files storage, if the asset doesn't have a `publicPath`.
For example:
```HTML+Django
{% load get_files from webpack_loader %}
{% get_files 'editor' 'css' as editor_css_files %}
CKEDITOR.config.contentsCss = '{{ editor_css_files.0.url }}';
<!-- or list down name and url for every file -->
<ul>
{% for css_file in editor_css_files %}
<li>{{ css_file.name }} : {{ css_file.url }}</li>
{% endfor %}
</ul>
```
### Code splitting
In case you wish to use [code-splitting](https://webpack.js.org/guides/code-splitting/), follow the recipe below on the Javascript side.
Create your entrypoint file and add elements to the DOM, while leveraging the lazy imports.
```js
// src/principal.js
function getComponent() {
return import(/* webpackChunkName: "lodash" */ 'lodash').then(({ default: _ }) => {
const element = document.createElement('div');
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}).catch(error => 'An error occurred while loading the component');
}
getComponent().then((component) => {
document.body.appendChild(component);
})
```
On your configuration file, do the following:
```js
// webpack.config.js
module.exports = {
context: __dirname,
entry: {
principal: './src/principal',
},
output: {
path: path.resolve('./dist/'),
// publicPath should match your STATIC_URL config.
// This is required otherwise webpack will try to fetch
// our chunk generated by the dynamic import from "/" instead of "/dist/".
publicPath: '/dist/',
chunkFilename: '[name].bundle.js',
filename: "[name]-[hash].js"
},
plugins: [
new BundleTracker({ filename: './webpack-stats.json' })
]
}
```
If you're using Webpack 5 instead of 4, do the following:
- Change `filename: "[name]-[hash].js"` to `filename: "[name]-[fullhash].js"`;
- Remove `/* webpackChunkName: "lodash" */`, which is not needed anymore.
On your template, render the bundle as usual:
```HTML+Django
<!-- index.html -->
{% load render_bundle from webpack_loader %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My test page</title>
</head>
<body>
<p>This is my page</p>
{% render_bundle 'principal' 'js' %}
</body>
</html>
```
### Hot reload
In case you wish to enable hot reload for your project using `django-webpack-loader` and `webpack-bundle-tracker`, please check out [this example](https://github.com/django-webpack/django-webpack-loader/tree/master/examples/hot-reload), in particular how [server.js](https://github.com/django-webpack/django-webpack-loader/blob/master/examples/hot-reload/server.js) and [webpack.config.js](https://github.com/django-webpack/django-webpack-loader/blob/master/examples/hot-reload/webpack.config.js) are configured.
### Jinja2 Configuration
If you need to output your assets in a jinja template, we provide a Jinja2 extension that's compatible with [django-jinja](https://github.com/niwinz/django-jinja).
To install the extension, add it to the `TEMPLATES` configuration in the `["OPTIONS"]["extension"]` list.
```python
from django_jinja.builtins import DEFAULT_EXTENSIONS
TEMPLATES = [
{
"BACKEND": "django_jinja.backend.Jinja2",
"OPTIONS": {
"extensions": DEFAULT_EXTENSIONS + [
"webpack_loader.contrib.jinja2ext.WebpackExtension",
],
}
}
]
```
Then in your base jinja template, do:
```HTML
{{ render_bundle('main') }}
```
## Migrating from version < 1.0.0
In order to use `django-webpack-loader>=1.0.0`, you must ensure that `webpack-bundle-tracker@1.0.0` is being used on the JavaScript side. It's recommended that you always keep at least minor version parity across both packages, for full compatibility.
This is necessary because the formatting of `webpack-stats.json` that `webpack-bundle-tracker` outputs has changed starting at version `1.0.0-alpha.1`. Starting at `django-webpack-loader==1.0.0`, this is the only formatting accepted here, meaning that other versions of that package don't output compatible files anymore, thereby breaking compatibility with older `webpack-bundle-tracker` releases.
## Commercial Support
[](https://www.vinta.com.br/)
This project is maintained by [Vinta Software](https://www.vinta.com.br/) and is used in products of Vinta's clients. We are always looking for exciting work, so if you need any commercial support, feel free to get in touch: contact@vinta.com.br
%package help
Summary: Development documents and examples for django-webpack-loader
Provides: python3-django-webpack-loader-doc
%description help
# django-webpack-loader
[](https://circleci.com/gh/django-webpack/django-webpack-loader/tree/master)
[](https://coveralls.io/github/django-webpack/django-webpack-loader?branch=master)


Use webpack to generate your static bundles without django's staticfiles or opaque wrappers.
Django webpack loader consumes the output generated by [webpack-bundle-tracker](https://github.com/owais/webpack-bundle-tracker) and lets you use the generated bundles in django.
A [changelog](CHANGELOG.md) is also available.
## Compatibility
Test cases cover Django>=2.0 on Python>=3.5. 100% code coverage is the target so we can be sure everything works anytime. It should probably work on older version of django as well but the package does not ship any test cases for them.
## Install
```bash
npm install --save-dev webpack-bundle-tracker
pip install django-webpack-loader
```
## Configuration
### Configuring `webpack-bundle-tracker`
Before configuring `django-webpack-loader`, let's first configure what's necessary on `webpack-bundle-tracker` side. Update your Webpack configuration file (it's usually on `webpack.config.js` in the project root). Make sure your file looks like this (adapt to your needs):
```javascript
const path = require('path');
const webpack = require('webpack');
const BundleTracker = require('webpack-bundle-tracker');
module.exports = {
context: __dirname,
entry: './assets/js/index',
output: {
path: path.resolve('./assets/webpack_bundles/'),
filename: "[name]-[hash].js"
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'})
],
}
```
The configuration above expects the `index.js` (the app entrypoint file) to live inside the `/assets/js/` directory (this guide going forward will assume that all front-end related files are placed inside the `/assets/` directory, with the different kinds of files arranged within its subdirectories).
The generated compiled files will be placed inside the `/assets/webpack_bundles/` directory and the file with the information regarding the bundles and assets (`webpack-stats.json`) will be stored in the project root.
### Compiling the front-end assets
You must generate the front-end bundle using `webpack-bundle-tracker` before using `django-webpack-loader`. You can compile the assets and generate the bundles by running:
```bash
npx webpack --config webpack.config.js --watch
```
This will also generate the stats file. You can also refer to how `django-react-boilerplate` configure the [package.json](https://github.com/vintasoftware/django-react-boilerplate/blob/master/package.json) scripts for different situations.
> ⚠️ Hot reload is available through a specific config. Check [this section](#hot-reload).
> ⚠️ This is the recommended usage for the development environment. For **usage in production**, please refer to [this section](#usage-in-production)
### Configuring the settings file
First of all, add `webpack_loader` to `INSTALLED_APPS`.
```python
INSTALLED_APPS = (
...
'webpack_loader',
...
)
```
Below is the recommended setup for the Django settings file when using `django-webpack-loader`.
```python
WEBPACK_LOADER = {
'DEFAULT': {
'CACHE': not DEBUG,
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
'POLL_INTERVAL': 0.1,
'IGNORE': [r'.+\.hot-update.js', r'.+\.map'],
}
}
```
For that setup, we're using the `DEBUG` variable provided by Django. Since in a production environment (`DEBUG = False`) the assets files won't constantly change, we can safely cache the results (`CACHE=True`) and optimize our flow, as `django-webpack-loader` will read the stats file only once and store the assets files paths in memory. From that point onwards, it will use these stored paths as the source of truth. If `CACHE=False`, we'll always read the stats file to get the assets paths.
> ⚠️ If `CACHE=True`, any changes made in the assets files will only be read when the web workers are restarted.
During development, when the stats file changes a lot, we want to always poll for its updated version (in our case, we'll fetch it every 0.1s, as defined on `POLL_INTERVAL`).
> ⚠️ In production (`DEBUG=False`), we'll only fetch the stats file once, so `POLL_INTERVAL` is ignored.
While `CACHE` isn't directly related to `POLL_INTERVAL`, it's interesting to keep `CACHE` binded to the `DEBUG` logic value (in this case, the negation of the logic value) in order to only cache the assets in production, as we'd not continuously poll the stats file in that environment.
The `STATS_FILE` parameter represents the output file produced by `webpack-bundle-tracker`. Since in the Webpack configuration file we've named it `webpack-stats.json` and stored it on the project root, we must replicate that setting on the back-end side.
`IGNORE` is a list of regular expressions. If a file generated by Webpack matches one of the expressions, the file will not be included in the template.
### Extra settings
- `TIMEOUT` is the number of seconds webpack_loader should wait for webpack to finish compiling before raising an exception. `0`, `None` or leaving the value out of settings disables timeouts
- `INTEGRITY` is flag enabling [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) on rendered `<script>` and `<link>` tags. Integrity hash is get from stats file and configuration on side of `BundleTracker`, where configuration option `integrity: true` is required.
- `LOADER_CLASS` is the fully qualified name of a python class as a string that holds the custom webpack loader. This is where behavior can be customized as to how the stats file is loaded. Examples include loading the stats file from a database, cache, external url, etc. For convenience, `webpack_loader.loader.WebpackLoader` can be extended. The `load_assets` method is likely where custom behavior will be added. This should return the stats file as an object.
- `SKIP_COMMON_CHUNKS` is a flag which prevents already generated chunks from being included again in the same page. This should only happen if you use more than one entrypoint per Django template (multiple `render_bundle` calls). By enabling this, you can get the same default behavior of the [HtmlWebpackPlugin](https://webpack.js.org/plugins/html-webpack-plugin/). The same caveats apply as when using `skip_common_chunks` on `render_bundle`, see that section below for more details.
Here's a simple example of loading from an external url:
```py
import requests
from webpack_loader.loader import WebpackLoader
class ExternalWebpackLoader(WebpackLoader):
def load_assets(self):
url = self.config['STATS_URL']
return requests.get(url).json()
```
## Rendering
In order to render the front-end code into the Django templates, we use the `render_bundle` template tag.
Its behavior is to accept a string with the name of an entrypoint from the stats file (in our case, we're using `main`, which is [the default](https://webpack.js.org/concepts/entry-points/#single-entry-shorthand-syntax)) and it'll proceed to include all files under that entrypoint. You can read more about the entrypoints concept [here](https://webpack.js.org/concepts/entry-points/).
> ⚠️ You can also check an example on how to use multiple `entry` values [here](https://github.com/django-webpack/django-webpack-loader/tree/master/examples/code-splitting).
Below is the basic usage for `render_bundle` within a template:
```HTML+Django
{% load render_bundle from webpack_loader %}
{% render_bundle 'main' %}
```
That will render the proper `<script>` and `<link>` tags needed in your template.
## Running in development
For `django-webpack-loader` to work, you must run the webpack pipeline. Please refer to [this section](#compiling-the-front-end-assets).
In summary, you should do the following:
```bash
# in one shell
npx webpack --config webpack.config.js --watch
# in another shell
python manage.py runserver
```
> ⚠️ You can also check [this example](https://github.com/django-webpack/django-webpack-loader/tree/master/examples/simple) on how to run a project with `django-webpack-loader` and `webpack-bundle-track`.
## Usage in production
We recommend that you keep your local bundles and the stats file outside the version control, having a production pipeline that will compile and collect the assets during the deployment phase.
You must add `STATICFILES_DIRS` to your settings file, pointing to the directory where the static files are located. This will let `collectstatic` know where it should look at:
```python
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)
```
Below are the commands that should be run to compile and collect the static files (please note this may change from platform to platform):
```
npm run build
python manage.py collectstatic --noinput
```
First we build the assets and, since we have `webpack-bundle-tracker` in our front-end building pipeline, the stats file will be populated. Then, we manually run collecstatic to collect the compiled assets.
> ⚠️ Heroku is one platform that automatically runs collectstatic for you, so you need to set `DISABLE_COLLECTSTATIC=1` environment var. Instead, you must manually run collectstatic after running webpack. In Heroku, this is achieved with a `post_compile` hook. You can see an example on how to implement this flow on [django-react-boilerplate](https://github.com/vintasoftware/django-react-boilerplate/tree/master/bin).
However, production usage for this package is **fairly flexible**. Other approaches may include keeping the production bundles in the version control and take that responsibility from the automatic pipeline. However, you must remember to always build the frontend and generate the bundle before pushing to remote.
## Usage in tests
To run tests where `render_bundle` shows up, since we don't have `webpack-bundle-tracker` at that point to generate the stats file, the calls to render the bundle will fail. The solution is to use the `FakeWebpackLoader` in your test settings:
```python
WEBPACK_LOADER['DEFAULT']['LOADER_CLASS'] = 'webpack_loader.loader.FakeWebpackLoader'
```
## Advanced Usage
### Rendering by file extension
`render_bundle` also takes a second argument which can be a file extension to match. This is useful when you want to render different types for files in separately. For example, to render CSS in head and JS at bottom we can do something like this,
```HTML+Django
{% load render_bundle from webpack_loader %}
<html>
<head>
{% render_bundle 'main' 'css' %}
</head>
<body>
....
{% render_bundle 'main' 'js' %}
</body>
</head>
```
### Using preload
The `is_preload=True` option in the `render_bundle` template tag can be used to add `rel="preload"` link tags.
```HTML+Django
{% load render_bundle from webpack_loader %}
<html>
<head>
{% render_bundle 'main' 'css' is_preload=True %}
{% render_bundle 'main' 'js' is_preload=True %}
{% render_bundle 'main' 'css' %}
</head>
<body>
{% render_bundle 'main' 'js' %}
</body>
</html>
```
### Accessing other webpack assets
`webpack_static` template tag provides facilities to load static assets managed by webpack in Django templates. It is like Django's built in `static` tag but for webpack assets instead.
In the below example, `logo.png` can be any static asset shipped with any npm package.
```HTML+Django
{% load webpack_static from webpack_loader %}
<!-- render full public path of logo.png -->
<img src="{% webpack_static 'logo.png' %}"/>
```
The public path is based on `webpack.config.js` [output.publicPath](https://webpack.js.org/configuration/output/#output-publicpath).
Please note that this approach will use the original asset file, and not a post-processed one from the Webpack pipeline, in case that file had gone through such flow (i.e.: You've imported an image on the React side and used it there, the file used within the React components will probably have a hash string on its name, etc. This processed file will be different than the one you'll grab with `webpack_static`).
### Use `skip_common_chunks` on `render_bundle`
You can use the parameter `skip_common_chunks=True` or `skip_common_chunks=False` to override the global `SKIP_COMMON_CHUNKS` setting for a specific bundle.
In order for this option to work, `django-webpack-loader` requires the `request` object to be in the context, to be able to keep track of the generated chunks.
The `request` object is passed by default via the `django.template.context_processors.request` middleware with using the Django built-in templating system, and also with using Jinja2.
If you don't have `request` in the context for some reason (e.g. using `Template.render` or `render_to_string` directly without passing the request), you'll get warnings on the console and the common chunks will remain duplicated.
### Appending file extensions
The `suffix` option can be used to append a string at the end of the file URL. For instance, it can be used if your webpack configuration emits compressed `.gz` files.
qwe
```HTML+Django
{% load render_bundle from webpack_loader %}
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
{% render_bundle 'main' 'css' %}
</head>
<body>
{% render_bundle 'main' 'js' suffix='.gz' %}
</body>
</html>
```
### Multiple Webpack configurations
Version 1.0 and up of `django-webpack-loader` also supports multiple Webpack configurations. The following configuration defines 2 Webpack stats files in settings and uses the `config` argument in the template tags to influence which stats file to load the bundles from.
```python
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
},
'DASHBOARD': {
'BUNDLE_DIR_NAME': 'dashboard_bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats-dashboard.json'),
}
}
```
```HTML+Django
{% load render_bundle from webpack_loader %}
<html>
<body>
....
{% render_bundle 'main' 'js' 'DEFAULT' %}
{% render_bundle 'main' 'js' 'DASHBOARD' %}
<!-- or render all files from a bundle -->
{% render_bundle 'main' config='DASHBOARD' %}
<!-- the following tags do the same thing -->
{% render_bundle 'main' 'css' 'DASHBOARD' %}
{% render_bundle 'main' extension='css' config='DASHBOARD' %}
{% render_bundle 'main' config='DASHBOARD' extension='css' %}
<!-- add some extra attributes to the tag -->
{% render_bundle 'main' 'js' 'DEFAULT' attrs='async charset="UTF-8"'%}
</body>
</head>
```
### File URLs instead of html tags
If you need the URL to an asset without the HTML tags, the `get_files` template tag can be used. A common use case is specifying the URL to a custom css file for a Javascript plugin.
`get_files` works exactly like `render_bundle` except it returns a list of matching files and lets you assign the list to a custom template variable.
Each object in the returned list has 2 properties:
1. `name`, which is the name of a chunk from the stats file;
2. `url`, which can be:
1. The `publicPath` if the asset has one;
2. The `path` to the asset in the static files storage, if the asset doesn't have a `publicPath`.
For example:
```HTML+Django
{% load get_files from webpack_loader %}
{% get_files 'editor' 'css' as editor_css_files %}
CKEDITOR.config.contentsCss = '{{ editor_css_files.0.url }}';
<!-- or list down name and url for every file -->
<ul>
{% for css_file in editor_css_files %}
<li>{{ css_file.name }} : {{ css_file.url }}</li>
{% endfor %}
</ul>
```
### Code splitting
In case you wish to use [code-splitting](https://webpack.js.org/guides/code-splitting/), follow the recipe below on the Javascript side.
Create your entrypoint file and add elements to the DOM, while leveraging the lazy imports.
```js
// src/principal.js
function getComponent() {
return import(/* webpackChunkName: "lodash" */ 'lodash').then(({ default: _ }) => {
const element = document.createElement('div');
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}).catch(error => 'An error occurred while loading the component');
}
getComponent().then((component) => {
document.body.appendChild(component);
})
```
On your configuration file, do the following:
```js
// webpack.config.js
module.exports = {
context: __dirname,
entry: {
principal: './src/principal',
},
output: {
path: path.resolve('./dist/'),
// publicPath should match your STATIC_URL config.
// This is required otherwise webpack will try to fetch
// our chunk generated by the dynamic import from "/" instead of "/dist/".
publicPath: '/dist/',
chunkFilename: '[name].bundle.js',
filename: "[name]-[hash].js"
},
plugins: [
new BundleTracker({ filename: './webpack-stats.json' })
]
}
```
If you're using Webpack 5 instead of 4, do the following:
- Change `filename: "[name]-[hash].js"` to `filename: "[name]-[fullhash].js"`;
- Remove `/* webpackChunkName: "lodash" */`, which is not needed anymore.
On your template, render the bundle as usual:
```HTML+Django
<!-- index.html -->
{% load render_bundle from webpack_loader %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My test page</title>
</head>
<body>
<p>This is my page</p>
{% render_bundle 'principal' 'js' %}
</body>
</html>
```
### Hot reload
In case you wish to enable hot reload for your project using `django-webpack-loader` and `webpack-bundle-tracker`, please check out [this example](https://github.com/django-webpack/django-webpack-loader/tree/master/examples/hot-reload), in particular how [server.js](https://github.com/django-webpack/django-webpack-loader/blob/master/examples/hot-reload/server.js) and [webpack.config.js](https://github.com/django-webpack/django-webpack-loader/blob/master/examples/hot-reload/webpack.config.js) are configured.
### Jinja2 Configuration
If you need to output your assets in a jinja template, we provide a Jinja2 extension that's compatible with [django-jinja](https://github.com/niwinz/django-jinja).
To install the extension, add it to the `TEMPLATES` configuration in the `["OPTIONS"]["extension"]` list.
```python
from django_jinja.builtins import DEFAULT_EXTENSIONS
TEMPLATES = [
{
"BACKEND": "django_jinja.backend.Jinja2",
"OPTIONS": {
"extensions": DEFAULT_EXTENSIONS + [
"webpack_loader.contrib.jinja2ext.WebpackExtension",
],
}
}
]
```
Then in your base jinja template, do:
```HTML
{{ render_bundle('main') }}
```
## Migrating from version < 1.0.0
In order to use `django-webpack-loader>=1.0.0`, you must ensure that `webpack-bundle-tracker@1.0.0` is being used on the JavaScript side. It's recommended that you always keep at least minor version parity across both packages, for full compatibility.
This is necessary because the formatting of `webpack-stats.json` that `webpack-bundle-tracker` outputs has changed starting at version `1.0.0-alpha.1`. Starting at `django-webpack-loader==1.0.0`, this is the only formatting accepted here, meaning that other versions of that package don't output compatible files anymore, thereby breaking compatibility with older `webpack-bundle-tracker` releases.
## Commercial Support
[](https://www.vinta.com.br/)
This project is maintained by [Vinta Software](https://www.vinta.com.br/) and is used in products of Vinta's clients. We are always looking for exciting work, so if you need any commercial support, feel free to get in touch: contact@vinta.com.br
%prep
%autosetup -n django-webpack-loader-1.8.1
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-django-webpack-loader -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Fri Apr 21 2023 Python_Bot <Python_Bot@openeuler.org> - 1.8.1-1
- Package Spec generated
|