Package: django-webpack-custom-loader
django-webpack-loaderReadhttp://owaislone.org/blog/webpack-plus-reactjs-and-django/for a detailed step by step guide on setting up webpack with django using this library.Use webpack to generate your static bundles without django's staticfiles or opaque wrappers.Django webpack loader consumes the output generated bywebpack-bundle-trackerand lets you use the generated bundles in django.Achangelogis also available.CompatibilityTest cases cover Django>=1.6 on Python 2.7 and Python>=3.4. 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.Installnpminstall--save-devwebpack-bundle-tracker

pipinstalldjango-webpack-loaderConfigurationAssumptionsAssumingBASE_DIRin settings refers to the root of your django app.importsysimportosBASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))Assumingassets/is insettings.STATICFILES_DIRSlikeSTATICFILES_DIRS=(os.path.join(BASE_DIR,'assets'),)Assuming your webpack config lives at./webpack.config.jsand looks like thisvarpath=require('path');varwebpack=require('webpack');varBundleTracker=require('webpack-bundle-tracker');module.exports={context:__dirname,entry:'./assets/js/index',output:{path:path.resolve('./assets/webpack_bundles/'),filename:"[name]-[hash].js"},plugins:[newBundleTracker({filename:'./webpack-stats.json'})]}Default ConfigurationWEBPACK_LOADER={'DEFAULT':{'CACHE':notDEBUG,'BUNDLE_DIR_NAME':'webpack_bundles/',# must end with slash'STATS_FILE':os.path.join(BASE_DIR,'webpack-stats.json'),'POLL_INTERVAL':0.1,'TIMEOUT':None,'IGNORE':[r'.+\.hot-update.js',r'.+\.map'],'LOADER_CLASS':'webpack_loader.loader.WebpackLoader',}}CACHEWEBPACK_LOADER={'DEFAULT':{'CACHE':notDEBUG}}WhenCACHEis set to True, webpack-loader will read the stats file only once and cache the result. This means web workers need to be restarted in order to pick up any changes made to the stats files.BUNDLE_DIR_NAMEWEBPACK_LOADER={'DEFAULT':{'BUNDLE_DIR_NAME':'bundles/'# end with slash}}BUNDLE_DIR_NAMErefers to the dir in which webpack outputs the bundles. It should not be the full path. If./assetsis one of your static dirs and webpack generates the bundles in./assets/output/bundles/, thenBUNDLE_DIR_NAMEshould beoutput/bundles/.If the bundle generates a file calledmain-cf4b5fab6e00a404e0c7.jsand your STATIC_URL is/static/, then the<script>tag will look like this<scripttype="text/javascript"src="/static/output/bundles/main-cf4b5fab6e00a404e0c7.js"/>STATS_FILEWEBPACK_LOADER={'DEFAULT':{'STATS_FILE':os.path.join(BASE_DIR,'webpack-stats.json')}}STATS_FILEis the filesystem path to the file generated bywebpack-bundle-trackerplugin. If you initializewebpack-bundle-trackerplugin like thisnewBundleTracker({filename:'./webpack-stats.json'})and your webpack config is located at/home/src/webpack.config.js, then the value ofSTATS_FILEshould be/home/src/webpack-stats.jsonIGNOREIGNOREis 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.POLL_INTERVALPOLL_INTERVALis the number of seconds webpack_loader should wait between polling the stats file. The stats file is polled every 100 miliseconds by default and any requests to are blocked while webpack compiles the bundles. You can reduce this if your bundles take shorter to compile.NOTE:Stats file is not polled when in production (DEBUG=False).TIMEOUTTIMEOUTis the number of seconds webpack_loader should wait for webpack to finish compiling before raising an exception.0,Noneor leaving the value out of settings disables timeouts.LOADER_CLASSLOADER_CLASSis 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.WebpackLoadercan be extended;
Theload_assetsmethod is likely where custom behavior will be added. This should return the stats file as an object.Here's a simple example of loading from an external url:# in app.moduleimportrequestsfromwebpack_loader.loaderimportWebpackLoaderclassExternalWebpackLoader(WebpackLoader):defload_assets(self):url=self.config['STATS_URL']returnrequests.get(url).json()# in app.settingsWEBPACK_LOADER={'DEFAULT':{'CACHE':False,'BUNDLE_DIR_NAME':'bundles/','LOADER_CLASS':'app.module.ExternalWebpackLoader',# Custom config setting made available in WebpackLoader's self.config'STATS_URL':'https://www.test.com/path/to/stats/',}}UsageManually run webpack to build assets.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. If you are new to webpack, check one of theexamples, readmy detailed blog postor checkwebpack docs.SettingsAddwebpack_loadertoINSTALLED_APPSINSTALLED_APPS = (
    ...
    'webpack_loader',
)Templates{%loadrender_bundlefromwebpack_loader%}{%render_bundle'main'%}render_bundlewill render the proper<script>and<link>tags needed in your template.render_bundlealso 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,{%loadrender_bundlefromwebpack_loader%}<html><head>{%render_bundle'main''css'%}</head><body>....{%render_bundle'main''js'%}</body></head>Multiple webpack projectsVersion 2.0 and up of webpack loader also supports multiple webpack configurations. The following configuration defines 2 webpack stats files in settings and uses theconfigargument in the template tags to influence which stats file to load the bundles from.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'),}}{%loadrender_bundlefromwebpack_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 tagsIf you need the URL to an asset without the HTML tags, theget_filestemplate tag can be used. A common use case is specifying the URL to a
custom css file for a Javascript plugin.get_filesworks exactly likerender_bundleexcept it returns a list of
matching files and lets you assign the list to a custom template variable. For example,{%get_files'editor''css'aseditor_css_files%}CKEDITOR.config.contentsCss = '{{editor_css_files.0.publicPath}}';<!-- or list down name, path and download url for every file --><ul>{%forcss_fileineditor_css_files%}<li>{{css_file.name}}:{{css_file.path}}:{{css_file.publicPath}}</li>{%endfor%}</ul>Refer other static assetswebpack_statictemplate tag provides facilities to load static assets managed by webpack
in django templates. It is like django's built instatictag but for webpack assets instead.In the below example,logo.pngcan be any static asset shipped with any npm or bower package.{%loadwebpack_staticfromwebpack_loader%}<!-- render full public path of logo.png --><imgsrc="{%webpack_static'logo.png'%}"/>The public path is based onwebpack.config.jsoutput.publicPath.From Python codeIf you want to access the webpack asset path information from your application code then you can use
the function in thewebpack_loader.utilsmodule.>>>utils.get_files('main')[{'url':'/static/bundles/main.js',u'path':u'/home/mike/root/projects/django-webpack-loader/tests/assets/bundles/main.js',u'name':u'main.js'},{'url':'/static/bundles/styles.css',u'path':u'/home/mike/root/projects/django-webpack-loader/tests/assets/bundles/styles.css',u'name':u'styles.css'}]>>>utils.get_as_tags('main')['<script type="text/javascript" src="/static/bundles/main.js" ></script>','<link type="text/css" href="/static/bundles/styles.css" rel="stylesheet" />']How to use in ProductionIt is up to you. There are a few ways to handle this. I like to have slightly separate configs for production and local. I tell git to ignore my local stats + bundle file but track the ones for production. Before pushing out newer version to production, I generate a new bundle using production config and commit the new stats file and bundle. I store the stats file and bundles in a directory that is added to theSTATICFILES_DIR. This gives me integration with collectstatic for free. The generated bundles are automatically collected to the target directory and synched to S3../webpack_production.config.jsvarconfig=require('./webpack.config.js');varBundleTracker=require('webpack-bundle-tracker');config.output.path=require('path').resolve('./assets/dist');config.plugins=[newBundleTracker({filename:'./webpack-stats-prod.json'})]// override any other settings here like using Uglify or other things that make sense for production environments.module.exports=config;settings.pyifnotDEBUG:WEBPACK_LOADER.update({'BUNDLE_DIR_NAME':'dist/','STATS_FILE':os.path.join(BASE_DIR,'webpack-stats-prod.json')})You can also simply generate the bundles on the server before running collectstatic if that works for you.ExtraJinja2 ConfigurationIf you need to output your assets in a jinja template we provide a Jinja2 extension that's compatible with theDjango Jinjamodule and Django 1.8.To install the extension add it to the django_jinjaTEMPLATESconfiguration in the["OPTIONS"]["extension"]list.TEMPLATES=[{"BACKEND":"django_jinja.backend.Jinja2","OPTIONS":{"extensions":["django_jinja.builtins.extensions.DjangoFiltersExtension","webpack_loader.contrib.jinja2ext.WebpackExtension",],}}]Then in your base jinja template:{{ render_bundle('main') }}Enjoy your webpack with django :)