Toby
Toby

Reputation: 13365

Webpack setup with Django

I working on a Vue app in Django via django-webpack-loader, running locally I'm able to get it to work by using the following in my base.html file:

{% load render_bundle from webpack_loader %}
...
...
{% render_bundle 'app' %}

However, in production this doesn't work - I believe because the webpack production config uses the CommonChunksPlugin to split the bundles into app, manifest and vendor.

There isn't much documentation online for merging Webpack with Django - I'm wondering if there is a way to include all chunks in the Django template.

Upvotes: 7

Views: 2372

Answers (3)

Gonçalo Peres
Gonçalo Peres

Reputation: 13582

According to django-webpack-loader README.md

Version 1.0 and up of django-webpack-loader also supports multiple Webpack configurations.

So one could use define 2 Webpack stats files in settings: one for normal, and one for stage / prod

WEBPACK_LOADER = {
    'STAGE_OR_PROD': {
        'BUNDLE_DIR_NAME': 'stage_or_prod_bundles/',
        'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats-stage-or-prod.json'),
    },
    'NORMAL': {
        'BUNDLE_DIR_NAME': 'normal_bundles/',
        'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats-normal.json'),
    }
}

and then one can use the config argument in the template tags to influence which stats file to load the bundles from

{% load render_bundle from webpack_loader %}

<html>
  <body>
    ....
    {% render_bundle 'main' 'js' 'STAGE_OR_PROD' %}
    {% render_bundle 'main' 'js' 'NORMAL' %}

Upvotes: 0

Toby
Toby

Reputation: 13365

The problem in the end was due to code splitting. In dev, a single JS file is created, but in the production config the Webpack CommonChunksPlugin was configured to split the app into 3 files (manifest, vendor and app).

This solution isn't ideal and might not scale well, but by placing a conditional tag in the Django template I was able to correctly reference the necessary files.

{% if STAGE or PRODUCTION %}
  {% render_bundle 'vendor' 'js' %}
  {% render_bundle 'manifest' 'js' %}
{% endif %}

{% render_bundle 'app' 'js' %}

Upvotes: 7

Leon Mak
Leon Mak

Reputation: 505

Did you edit settings.py to point to the bundle directory?

APP_DIR = os.path.join(BASE_DIR, 'app')
WEBPACK_LOADER = {
    'DEFAULT': {
        'BUNDLE_DIR_NAME': 'dist/'
    }
}

STATICFILES_DIRS = (
    os.path.join(APP_DIR, 'assets'),
)

Then use HtmlWebpackPlugin to point to chunks? https://github.com/jantimon/html-webpack-plugin/blob/master/README.md#writing-your-own-templates

plugins: [
    new HtmlWebpackPlugin({
      template: 'static/app/index.html'
    }), 
]

Upvotes: 1

Related Questions