django-webpack-loader-0.5.0/0000755000076500000240000000000013107756206016110 5ustar owaisstaff00000000000000django-webpack-loader-0.5.0/django_webpack_loader.egg-info/0000755000076500000240000000000013107756206024066 5ustar owaisstaff00000000000000django-webpack-loader-0.5.0/django_webpack_loader.egg-info/dependency_links.txt0000644000076500000240000000000113107756206030134 0ustar owaisstaff00000000000000 django-webpack-loader-0.5.0/django_webpack_loader.egg-info/PKG-INFO0000644000076500000240000004206613107756206025173 0ustar owaisstaff00000000000000Metadata-Version: 1.1 Name: django-webpack-loader Version: 0.5.0 Summary: Transparently use webpack with django Home-page: https://github.com/owais/django-webpack-loader Author: Owais Lone Author-email: hello@owaislone.org License: UNKNOWN Download-URL: https://github.com/owais/django-webpack-loader/tarball/0.5.0 Description: django-webpack-loader ===================== |Join the chat at https://gitter.im/owais/django-webpack-loader| |Build Status| |Coverage Status| Read http://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 by `webpack-bundle-tracker `__ and lets you use the generated bundles in django. Maintainers ----------- In order to overcome the lack of support for Markdown on PyPi, building this package can use `pandoc `__ along with `pypandoc `__ to convert the README.md into a Restructured Text format compatible with PyPI. This requires installing ``pandoc`` for your operating system (installation instructions on the pandoc site), and ``pypandoc`` which will be installed if you: :: pip install -r requirements-dev.txt before uploading to PyPI. If pandoc or pypandoc fails, the README.md file will be uploaded as it was before this enhancement. Compatibility ------------- Test cases cover Django>=1.6 on Python 2.7 and Python>=3.3. 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 ------- .. code:: bash npm install --save-dev webpack-bundle-tracker pip install django-webpack-loader Configuration ------------- Assumptions ~~~~~~~~~~~ Assuming ``BASE_DIR`` in settings refers to the root of your django app. .. code:: python import sys import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) Assuming ``assets/`` is in ``settings.STATICFILES_DIRS`` like .. code:: python STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) Assuming your webpack config lives at ``./webpack.config.js`` and looks like this .. code:: javascript var path = require('path'); var webpack = require('webpack'); var 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'}) ] } Default Configuration ~~~~~~~~~~~~~~~~~~~~~ .. code:: python WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, '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': ['.+\.hot-update.js', '.+\.map'] } } CACHE ^^^^^ .. code:: python WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG } } When ``CACHE`` is 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\_NAME ^^^^^^^^^^^^^^^^^ .. code:: python WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/' # end with slash } } ``BUNDLE_DIR_NAME`` refers to the dir in which webpack outputs the bundles. It should not be the full path. If ``./assets`` is one of you static dirs and webpack generates the bundles in ``./assets/output/bundles/``, then ``BUNDLE_DIR_NAME`` should be ``output/bundles/``. If the bundle generates a file called ``main-cf4b5fab6e00a404e0c7.js`` and your STATIC\_URL is ``/static/``, then the ``', ''] How to use in Production ------------------------ **It 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 the ``STATICFILES_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.js`` .. code:: javascript var config = require('./webpack.config.js'); var BundleTracker = require('webpack-bundle-tracker'); config.output.path = require('path').resolve('./assets/dist'); config.plugins = [ new BundleTracker({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.py`` .. code:: python if not DEBUG: 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. Extra ----- Jinja2 Configuration ~~~~~~~~~~~~~~~~~~~~ If you need to output your assets in a jinja template we provide a Jinja2 extension that's compatible with the `Django Jinja `__ module and Django 1.8. To install the extension add it to the django\_jinja ``TEMPLATES`` configuration in the ``["OPTIONS"]["extension"]`` list. .. code:: python TEMPLATES = [ { "BACKEND": "django_jinja.backend.Jinja2", "OPTIONS": { "extensions": [ "django_jinja.builtins.extensions.DjangoFiltersExtension", "webpack_loader.contrib.jinja2ext.WebpackExtension", ], } } ] Then in your base jinja template: .. code:: html {{ render_bundle('main') }} -------------- Enjoy your webpack with django :) .. |Join the chat at https://gitter.im/owais/django-webpack-loader| image:: https://badges.gitter.im/Join%20Chat.svg :target: https://gitter.im/owais/django-webpack-loader?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge .. |Build Status| image:: https://travis-ci.org/owais/django-webpack-loader.svg?branch=master :target: https://travis-ci.org/owais/django-webpack-loader .. |Coverage Status| image:: https://coveralls.io/repos/owais/django-webpack-loader/badge.svg?branch=master&service=github :target: https://coveralls.io/github/owais/django-webpack-loader?branch=master Keywords: django,webpack,assets Platform: UNKNOWN Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Framework :: Django Classifier: Environment :: Web Environment Classifier: License :: OSI Approved :: MIT License django-webpack-loader-0.5.0/django_webpack_loader.egg-info/SOURCES.txt0000644000076500000240000000113013107756206025745 0ustar owaisstaff00000000000000LICENSE MANIFEST.in README.md README.rst setup.cfg setup.py django_webpack_loader.egg-info/PKG-INFO django_webpack_loader.egg-info/SOURCES.txt django_webpack_loader.egg-info/dependency_links.txt django_webpack_loader.egg-info/top_level.txt webpack_loader/__init__.py webpack_loader/apps.py webpack_loader/config.py webpack_loader/errors.py webpack_loader/exceptions.py webpack_loader/loader.py webpack_loader/signals.py webpack_loader/utils.py webpack_loader/contrib/__init__.py webpack_loader/contrib/jinja2ext.py webpack_loader/templatetags/__init__.py webpack_loader/templatetags/webpack_loader.pydjango-webpack-loader-0.5.0/django_webpack_loader.egg-info/top_level.txt0000644000076500000240000000010213107756206026611 0ustar owaisstaff00000000000000webpack_loader webpack_loader/contrib webpack_loader/templatetags django-webpack-loader-0.5.0/LICENSE0000644000076500000240000000206612745214412017114 0ustar owaisstaff00000000000000The MIT License (MIT) Copyright (c) 2015 Owais Lone Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. django-webpack-loader-0.5.0/MANIFEST.in0000644000076500000240000000004212745070670017643 0ustar owaisstaff00000000000000include LICENSE include README.md django-webpack-loader-0.5.0/PKG-INFO0000644000076500000240000004206613107756206017215 0ustar owaisstaff00000000000000Metadata-Version: 1.1 Name: django-webpack-loader Version: 0.5.0 Summary: Transparently use webpack with django Home-page: https://github.com/owais/django-webpack-loader Author: Owais Lone Author-email: hello@owaislone.org License: UNKNOWN Download-URL: https://github.com/owais/django-webpack-loader/tarball/0.5.0 Description: django-webpack-loader ===================== |Join the chat at https://gitter.im/owais/django-webpack-loader| |Build Status| |Coverage Status| Read http://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 by `webpack-bundle-tracker `__ and lets you use the generated bundles in django. Maintainers ----------- In order to overcome the lack of support for Markdown on PyPi, building this package can use `pandoc `__ along with `pypandoc `__ to convert the README.md into a Restructured Text format compatible with PyPI. This requires installing ``pandoc`` for your operating system (installation instructions on the pandoc site), and ``pypandoc`` which will be installed if you: :: pip install -r requirements-dev.txt before uploading to PyPI. If pandoc or pypandoc fails, the README.md file will be uploaded as it was before this enhancement. Compatibility ------------- Test cases cover Django>=1.6 on Python 2.7 and Python>=3.3. 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 ------- .. code:: bash npm install --save-dev webpack-bundle-tracker pip install django-webpack-loader Configuration ------------- Assumptions ~~~~~~~~~~~ Assuming ``BASE_DIR`` in settings refers to the root of your django app. .. code:: python import sys import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) Assuming ``assets/`` is in ``settings.STATICFILES_DIRS`` like .. code:: python STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) Assuming your webpack config lives at ``./webpack.config.js`` and looks like this .. code:: javascript var path = require('path'); var webpack = require('webpack'); var 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'}) ] } Default Configuration ~~~~~~~~~~~~~~~~~~~~~ .. code:: python WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, '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': ['.+\.hot-update.js', '.+\.map'] } } CACHE ^^^^^ .. code:: python WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG } } When ``CACHE`` is 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\_NAME ^^^^^^^^^^^^^^^^^ .. code:: python WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/' # end with slash } } ``BUNDLE_DIR_NAME`` refers to the dir in which webpack outputs the bundles. It should not be the full path. If ``./assets`` is one of you static dirs and webpack generates the bundles in ``./assets/output/bundles/``, then ``BUNDLE_DIR_NAME`` should be ``output/bundles/``. If the bundle generates a file called ``main-cf4b5fab6e00a404e0c7.js`` and your STATIC\_URL is ``/static/``, then the ``', ''] How to use in Production ------------------------ **It 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 the ``STATICFILES_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.js`` .. code:: javascript var config = require('./webpack.config.js'); var BundleTracker = require('webpack-bundle-tracker'); config.output.path = require('path').resolve('./assets/dist'); config.plugins = [ new BundleTracker({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.py`` .. code:: python if not DEBUG: 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. Extra ----- Jinja2 Configuration ~~~~~~~~~~~~~~~~~~~~ If you need to output your assets in a jinja template we provide a Jinja2 extension that's compatible with the `Django Jinja `__ module and Django 1.8. To install the extension add it to the django\_jinja ``TEMPLATES`` configuration in the ``["OPTIONS"]["extension"]`` list. .. code:: python TEMPLATES = [ { "BACKEND": "django_jinja.backend.Jinja2", "OPTIONS": { "extensions": [ "django_jinja.builtins.extensions.DjangoFiltersExtension", "webpack_loader.contrib.jinja2ext.WebpackExtension", ], } } ] Then in your base jinja template: .. code:: html {{ render_bundle('main') }} -------------- Enjoy your webpack with django :) .. |Join the chat at https://gitter.im/owais/django-webpack-loader| image:: https://badges.gitter.im/Join%20Chat.svg :target: https://gitter.im/owais/django-webpack-loader?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge .. |Build Status| image:: https://travis-ci.org/owais/django-webpack-loader.svg?branch=master :target: https://travis-ci.org/owais/django-webpack-loader .. |Coverage Status| image:: https://coveralls.io/repos/owais/django-webpack-loader/badge.svg?branch=master&service=github :target: https://coveralls.io/github/owais/django-webpack-loader?branch=master Keywords: django,webpack,assets Platform: UNKNOWN Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Framework :: Django Classifier: Environment :: Web Environment Classifier: License :: OSI Approved :: MIT License django-webpack-loader-0.5.0/README.md0000644000076500000240000002747113107033304017365 0ustar owaisstaff00000000000000# django-webpack-loader [![Join the chat at https://gitter.im/owais/django-webpack-loader](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/owais/django-webpack-loader?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://travis-ci.org/owais/django-webpack-loader.svg?branch=master)](https://travis-ci.org/owais/django-webpack-loader) [![Coverage Status](https://coveralls.io/repos/owais/django-webpack-loader/badge.svg?branch=master&service=github)](https://coveralls.io/github/owais/django-webpack-loader?branch=master)
Read http://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 by [webpack-bundle-tracker](https://github.com/owais/webpack-bundle-tracker) and lets you use the generated bundles in django. ## Maintainers In order to overcome the lack of support for Markdown on PyPi, building this package can use [pandoc](http://pandoc.org/installing.html) along with [pypandoc](https://pypi.python.org/pypi/pypandoc) to convert the README.md into a Restructured Text format compatible with PyPI. This requires installing `pandoc` for your operating system (installation instructions on the pandoc site), and `pypandoc` which will be installed if you: pip install -r requirements-dev.txt before uploading to PyPI. If pandoc or pypandoc fails, the README.md file will be uploaded as it was before this enhancement. ## Compatibility Test cases cover Django>=1.6 on Python 2.7 and Python>=3.3. 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
### Assumptions Assuming `BASE_DIR` in settings refers to the root of your django app. ```python import sys import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ```
Assuming `assets/` is in `settings.STATICFILES_DIRS` like ```python STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) ```
Assuming your webpack config lives at `./webpack.config.js` and looks like this ```javascript var path = require('path'); var webpack = require('webpack'); var 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'}) ] } ```
### Default Configuration ```python WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, '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': ['.+\.hot-update.js', '.+\.map'] } } ```
#### CACHE ```python WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG } } ``` When `CACHE` is 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_NAME ```python WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/' # end with slash } } ``` `BUNDLE_DIR_NAME` refers to the dir in which webpack outputs the bundles. It should not be the full path. If `./assets` is one of you static dirs and webpack generates the bundles in `./assets/output/bundles/`, then `BUNDLE_DIR_NAME` should be `output/bundles/`. If the bundle generates a file called `main-cf4b5fab6e00a404e0c7.js` and your STATIC_URL is `/static/`, then the `', ''] ``` ## How to use in Production **It 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 the `STATICFILES_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.js` ```javascript var config = require('./webpack.config.js'); var BundleTracker = require('webpack-bundle-tracker'); config.output.path = require('path').resolve('./assets/dist'); config.plugins = [ new BundleTracker({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.py` ```python if not DEBUG: 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. ## Extra ### Jinja2 Configuration If you need to output your assets in a jinja template we provide a Jinja2 extension that's compatible with the [Django Jinja](https://github.com/niwinz/django-jinja) module and Django 1.8. To install the extension add it to the django_jinja `TEMPLATES` configuration in the `["OPTIONS"]["extension"]` list. ```python TEMPLATES = [ { "BACKEND": "django_jinja.backend.Jinja2", "OPTIONS": { "extensions": [ "django_jinja.builtins.extensions.DjangoFiltersExtension", "webpack_loader.contrib.jinja2ext.WebpackExtension", ], } } ] ``` Then in your base jinja template: ```HTML {{ render_bundle('main') }} ``` --------------------
Enjoy your webpack with django :) django-webpack-loader-0.5.0/README.rst0000644000076500000240000003153313107756205017603 0ustar owaisstaff00000000000000django-webpack-loader ===================== |Join the chat at https://gitter.im/owais/django-webpack-loader| |Build Status| |Coverage Status| Read http://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 by `webpack-bundle-tracker `__ and lets you use the generated bundles in django. Maintainers ----------- In order to overcome the lack of support for Markdown on PyPi, building this package can use `pandoc `__ along with `pypandoc `__ to convert the README.md into a Restructured Text format compatible with PyPI. This requires installing ``pandoc`` for your operating system (installation instructions on the pandoc site), and ``pypandoc`` which will be installed if you: :: pip install -r requirements-dev.txt before uploading to PyPI. If pandoc or pypandoc fails, the README.md file will be uploaded as it was before this enhancement. Compatibility ------------- Test cases cover Django>=1.6 on Python 2.7 and Python>=3.3. 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 ------- .. code:: bash npm install --save-dev webpack-bundle-tracker pip install django-webpack-loader Configuration ------------- Assumptions ~~~~~~~~~~~ Assuming ``BASE_DIR`` in settings refers to the root of your django app. .. code:: python import sys import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) Assuming ``assets/`` is in ``settings.STATICFILES_DIRS`` like .. code:: python STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) Assuming your webpack config lives at ``./webpack.config.js`` and looks like this .. code:: javascript var path = require('path'); var webpack = require('webpack'); var 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'}) ] } Default Configuration ~~~~~~~~~~~~~~~~~~~~~ .. code:: python WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, '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': ['.+\.hot-update.js', '.+\.map'] } } CACHE ^^^^^ .. code:: python WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG } } When ``CACHE`` is 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\_NAME ^^^^^^^^^^^^^^^^^ .. code:: python WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/' # end with slash } } ``BUNDLE_DIR_NAME`` refers to the dir in which webpack outputs the bundles. It should not be the full path. If ``./assets`` is one of you static dirs and webpack generates the bundles in ``./assets/output/bundles/``, then ``BUNDLE_DIR_NAME`` should be ``output/bundles/``. If the bundle generates a file called ``main-cf4b5fab6e00a404e0c7.js`` and your STATIC\_URL is ``/static/``, then the ``', ''] How to use in Production ------------------------ **It 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 the ``STATICFILES_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.js`` .. code:: javascript var config = require('./webpack.config.js'); var BundleTracker = require('webpack-bundle-tracker'); config.output.path = require('path').resolve('./assets/dist'); config.plugins = [ new BundleTracker({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.py`` .. code:: python if not DEBUG: 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. Extra ----- Jinja2 Configuration ~~~~~~~~~~~~~~~~~~~~ If you need to output your assets in a jinja template we provide a Jinja2 extension that's compatible with the `Django Jinja `__ module and Django 1.8. To install the extension add it to the django\_jinja ``TEMPLATES`` configuration in the ``["OPTIONS"]["extension"]`` list. .. code:: python TEMPLATES = [ { "BACKEND": "django_jinja.backend.Jinja2", "OPTIONS": { "extensions": [ "django_jinja.builtins.extensions.DjangoFiltersExtension", "webpack_loader.contrib.jinja2ext.WebpackExtension", ], } } ] Then in your base jinja template: .. code:: html {{ render_bundle('main') }} -------------- Enjoy your webpack with django :) .. |Join the chat at https://gitter.im/owais/django-webpack-loader| image:: https://badges.gitter.im/Join%20Chat.svg :target: https://gitter.im/owais/django-webpack-loader?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge .. |Build Status| image:: https://travis-ci.org/owais/django-webpack-loader.svg?branch=master :target: https://travis-ci.org/owais/django-webpack-loader .. |Coverage Status| image:: https://coveralls.io/repos/owais/django-webpack-loader/badge.svg?branch=master&service=github :target: https://coveralls.io/github/owais/django-webpack-loader?branch=master django-webpack-loader-0.5.0/setup.cfg0000644000076500000240000000012013107756206017722 0ustar owaisstaff00000000000000[metadata] description-file = README.rst [egg_info] tag_build = tag_date = 0 django-webpack-loader-0.5.0/setup.py0000644000076500000240000000260313107033304017606 0ustar owaisstaff00000000000000import os import re from setuptools import setup def rel(*parts): '''returns the relative path to a file wrt to the current directory''' return os.path.abspath(os.path.join(os.path.dirname(__file__), *parts)) if os.path.isfile('README.rst'): README = open('README.rst', 'r').read() else: README = open('README.md', 'r').read() with open(rel('webpack_loader', '__init__.py')) as handler: INIT_PY = handler.read() VERSION = re.findall("__version__ = '([^']+)'", INIT_PY)[0] setup( name = 'django-webpack-loader', packages = ['webpack_loader', 'webpack_loader/templatetags', 'webpack_loader/contrib'], version = VERSION, description = 'Transparently use webpack with django', long_description=README, author = 'Owais Lone', author_email = 'hello@owaislone.org', download_url = 'https://github.com/owais/django-webpack-loader/tarball/{0}'.format(VERSION), url = 'https://github.com/owais/django-webpack-loader', # use the URL to the github repo keywords = ['django', 'webpack', 'assets'], # arbitrary keywords classifiers = [ 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Framework :: Django', 'Environment :: Web Environment', 'License :: OSI Approved :: MIT License', ], ) django-webpack-loader-0.5.0/webpack_loader/0000755000076500000240000000000013107756206021052 5ustar owaisstaff00000000000000django-webpack-loader-0.5.0/webpack_loader/__init__.py0000644000076500000240000000016013107306303023145 0ustar owaisstaff00000000000000__author__ = 'Owais Lone' __version__ = '0.5.0' default_app_config = 'webpack_loader.apps.WebpackLoaderConfig' django-webpack-loader-0.5.0/webpack_loader/apps.py0000644000076500000240000000135013107306051022353 0ustar owaisstaff00000000000000from django.apps import AppConfig from .errors import BAD_CONFIG_ERROR def webpack_cfg_check(*args, **kwargs): '''Test if config is compatible or not''' from django.conf import settings check_failed = False user_config = getattr(settings, 'WEBPACK_LOADER', {}) try: user_config = [dict({}, **cfg) for cfg in user_config.values()] except TypeError: check_failed = True errors = [] if check_failed: errors.append(BAD_CONFIG_ERROR) return errors class WebpackLoaderConfig(AppConfig): name = 'webpack_loader' verbose_name = "Webpack Loader" def ready(self): from django.core.checks import register, Tags register(Tags.compatibility)(webpack_cfg_check) django-webpack-loader-0.5.0/webpack_loader/config.py0000644000076500000240000000133413056514412022664 0ustar owaisstaff00000000000000import re from django.conf import settings __all__ = ('load_config',) DEFAULT_CONFIG = { 'DEFAULT': { 'CACHE': not settings.DEBUG, 'BUNDLE_DIR_NAME': 'webpack_bundles/', 'STATS_FILE': 'webpack-stats.json', # FIXME: Explore usage of fsnotify 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, 'IGNORE': ['.+\.hot-update.js', '.+\.map'] } } user_config = getattr(settings, 'WEBPACK_LOADER', DEFAULT_CONFIG) user_config = dict( (name, dict(DEFAULT_CONFIG['DEFAULT'], **cfg)) for name, cfg in user_config.items() ) for entry in user_config.values(): entry['ignores'] = [re.compile(I) for I in entry['IGNORE']] def load_config(name): return user_config[name] django-webpack-loader-0.5.0/webpack_loader/contrib/0000755000076500000240000000000013107756206022512 5ustar owaisstaff00000000000000django-webpack-loader-0.5.0/webpack_loader/contrib/__init__.py0000644000076500000240000000000012560346352024610 0ustar owaisstaff00000000000000django-webpack-loader-0.5.0/webpack_loader/contrib/jinja2ext.py0000644000076500000240000000050112560346352024755 0ustar owaisstaff00000000000000import jinja2.ext from ..templatetags.webpack_loader import render_bundle class WebpackExtension(jinja2.ext.Extension): def __init__(self, environment): super(WebpackExtension, self).__init__(environment) environment.globals["render_bundle"] = lambda *a, **k: jinja2.Markup(render_bundle(*a, **k)) django-webpack-loader-0.5.0/webpack_loader/errors.py0000644000076500000240000000037313056512237022740 0ustar owaisstaff00000000000000from django.core.checks import Error BAD_CONFIG_ERROR = Error( 'Error while parsing WEBPACK_LOADER configuration', hint='Is WEBPACK_LOADER config valid?', obj='django.conf.settings.WEBPACK_LOADER', id='django-webpack-loader.E001', ) django-webpack-loader-0.5.0/webpack_loader/exceptions.py0000644000076500000240000000052313004143643023574 0ustar owaisstaff00000000000000__all__ = ( 'WebpackError', 'WebpackLoaderBadStatsError', 'WebpackLoaderTimeoutError', 'WebpackBundleLookupError' ) class WebpackError(Exception): pass class WebpackLoaderBadStatsError(Exception): pass class WebpackLoaderTimeoutError(Exception): pass class WebpackBundleLookupError(Exception): pass django-webpack-loader-0.5.0/webpack_loader/loader.py0000644000076500000240000000650613107306051022666 0ustar owaisstaff00000000000000import json import time from django.conf import settings from django.contrib.staticfiles.storage import staticfiles_storage from .exceptions import ( WebpackError, WebpackLoaderBadStatsError, WebpackLoaderTimeoutError, WebpackBundleLookupError ) from .config import load_config class WebpackLoader(object): _assets = {} def __init__(self, name='DEFAULT'): self.name = name self.config = load_config(self.name) def _load_assets(self): try: with open(self.config['STATS_FILE']) as f: return json.load(f) except IOError: raise IOError( 'Error reading {0}. Are you sure webpack has generated ' 'the file and the path is correct?'.format( self.config['STATS_FILE'])) def get_assets(self): if self.config['CACHE']: if self.name not in self._assets: self._assets[self.name] = self._load_assets() return self._assets[self.name] return self._load_assets() def filter_chunks(self, chunks): for chunk in chunks: ignore = any(regex.match(chunk['name']) for regex in self.config['ignores']) if not ignore: chunk['url'] = self.get_chunk_url(chunk) yield chunk def get_chunk_url(self, chunk): public_path = chunk.get('publicPath') if public_path: return public_path relpath = '{0}{1}'.format( self.config['BUNDLE_DIR_NAME'], chunk['name'] ) return staticfiles_storage.url(relpath) def get_bundle(self, bundle_name): assets = self.get_assets() # poll when debugging and block request until bundle is compiled # or the build times out if settings.DEBUG: timeout = self.config['TIMEOUT'] or 0 timed_out = False start = time.time() while assets['status'] == 'compiling' and not timed_out: time.sleep(self.config['POLL_INTERVAL']) if timeout and (time.time() - timeout > start): timed_out = True assets = self.get_assets() if timed_out: raise WebpackLoaderTimeoutError( "Timed Out. Bundle `{0}` took more than {1} seconds " "to compile.".format(bundle_name, timeout) ) if assets.get('status') == 'done': chunks = assets['chunks'].get(bundle_name, None) if chunks is None: raise WebpackBundleLookupError('Cannot resolve bundle {0}.'.format(bundle_name)) return self.filter_chunks(chunks) elif assets.get('status') == 'error': if 'file' not in assets: assets['file'] = '' if 'error' not in assets: assets['error'] = 'Unknown Error' if 'message' not in assets: assets['message'] = '' error = u""" {error} in {file} {message} """.format(**assets) raise WebpackError(error) raise WebpackLoaderBadStatsError( "The stats file does not contain valid data. Make sure " "webpack-bundle-tracker plugin is enabled and try to run " "webpack again.") django-webpack-loader-0.5.0/webpack_loader/signals.py0000644000076500000240000000003712560346352023063 0ustar owaisstaff00000000000000# will hook into collectstatic django-webpack-loader-0.5.0/webpack_loader/templatetags/0000755000076500000240000000000013107756206023544 5ustar owaisstaff00000000000000django-webpack-loader-0.5.0/webpack_loader/templatetags/__init__.py0000644000076500000240000000000012560346352025642 0ustar owaisstaff00000000000000django-webpack-loader-0.5.0/webpack_loader/templatetags/webpack_loader.py0000644000076500000240000000224313107306051027046 0ustar owaisstaff00000000000000from django import template, VERSION from django.conf import settings from django.utils.safestring import mark_safe from .. import utils register = template.Library() @register.simple_tag def render_bundle(bundle_name, extension=None, config='DEFAULT', attrs=''): tags = utils.get_as_tags(bundle_name, extension=extension, config=config, attrs=attrs) return mark_safe('\n'.join(tags)) @register.simple_tag def webpack_static(asset_name, config='DEFAULT'): return utils.get_static(asset_name, config=config) assignment_tag = register.simple_tag if VERSION >= (1, 9) else register.assignment_tag @assignment_tag def get_files(bundle_name, extension=None, config='DEFAULT'): """ Returns all chunks in the given bundle. Example usage:: {% get_files 'editor' 'css' as editor_css_chunks %} CKEDITOR.config.contentsCss = '{{ editor_css_chunks.0.publicPath }}'; :param bundle_name: The name of the bundle :param extension: (optional) filter by extension :param config: (optional) the name of the configuration :return: a list of matching chunks """ return utils.get_files(bundle_name, extension=extension, config=config) django-webpack-loader-0.5.0/webpack_loader/utils.py0000644000076500000240000000423313107306051022553 0ustar owaisstaff00000000000000from django.conf import settings from .loader import WebpackLoader _loaders = {} def get_loader(config_name): if config_name not in _loaders: _loaders[config_name] = WebpackLoader(config_name) return _loaders[config_name] def _filter_by_extension(bundle, extension): '''Return only files with the given extension''' for chunk in bundle: if chunk['name'].endswith('.{0}'.format(extension)): yield chunk def _get_bundle(bundle_name, extension, config): bundle = get_loader(config).get_bundle(bundle_name) if extension: bundle = _filter_by_extension(bundle, extension) return bundle def get_files(bundle_name, extension=None, config='DEFAULT'): '''Returns list of chunks from named bundle''' return list(_get_bundle(bundle_name, extension, config)) def get_as_tags(bundle_name, extension=None, config='DEFAULT', attrs=''): ''' Get a list of formatted ' ).format(chunk['url'], attrs)) elif chunk['name'].endswith(('.css', '.css.gz')): tags.append(( '' ).format(chunk['url'], attrs)) return tags def get_static(asset_name, config='DEFAULT'): ''' Equivalent to Django's 'static' look up but for webpack assets. :param asset_name: the name of the asset :param config: (optional) the name of the configuration :return: path to webpack asset as a string ''' return "{0}{1}".format( get_loader(config).get_assets().get( 'publicPath', getattr(settings, 'STATIC_URL') ), asset_name )