Skip to content

Instantly share code, notes, and snippets.

@LensHunnel
Last active May 18, 2020 12:18
Show Gist options
  • Save LensHunnel/790202269ec58fc1b9cad48247cf6514 to your computer and use it in GitHub Desktop.
Save LensHunnel/790202269ec58fc1b9cad48247cf6514 to your computer and use it in GitHub Desktop.
Step to use webpack, django and vue js

Steps to use Django with webpack and Vuejs

Requirements

  • python-vuejs:
 pip install python-vuejs
  • webpack-bundle-tracker
 npm install --save-dev webpack-bundle-tracker
  • django-webpack-loader
 pip install django-webpack-loader

Steps

  • Install the app, there is two ways to do that:

    • if django app already exists, run in the app folder:
      pyvue startvueapp .
    • else, in django root, run the following command:
      pyvue djstartvueapp 'app_name'
  • Add django-webpack-loader to INSTALLED_APPS

# in ./my_project/settings.py
INSTALLED_APPS = [
    'webpack_loader',
]
  • Configure webpack to use BundleTracker.
// build/webpack.base.conf.js
let BundleTracker = require('webpack-bundle-tracker')
module.exports = {
  // ...
  plugins: [
    new BundleTracker({filename: './webpack-stats.json'}),
  ],
  • Configure webpack to serve static assets
// ./config/index.js
module.exports = {
  build: {
    assetsRoot: path.resolve(__dirname, '../static/'),
    assetsSubDirectory: 'app_name',
    assetsPublicPath: '/static/',
    // ...
  },
  dev: {
    assetsPublicPath: 'http://localhost:8080/',
    // ...
  }
}
  • Add alias to resolve static in Vue component file
// build/webpack.base.conf.js
module.exports = {
  resolve: {
    alias: {
      // ...
      '__STATIC__': resolve('static'),
    },
}
  • Add following to allow dev server to accept CORS
// build/webpack.dev.conf.js
devServer: {
  headers: {
    "Access-Control-Allow-Origin":"\*"
  },
  // ...
}
  • Configure django static root and url
 STATIC_ROOT = os.path.join(BASE_DIR, 'static')
 STATIC_URL = '/static/'
  • Django template:
<!-- ./templates/my_project/base.html -->
{% load render_bundle from webpack_loader %}
<html>
  <body>
    {% block content %}
    {% endblock %}
    {% render_bundle 'app' %}
  </body>
</html>

<!-- ./templates/my_project/spa.html -->
{% extends "my_project/base.html" %}
{% block content %}
  <div id="app"></div>
{% endblock %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment