Note: This guide has been updated for use with @vue/cli
version 4! Please make sure you're using the latest version of @vue/cli
.
When it comes to starting new Vue projects, you can't really beat Vue CLI. The Vue team has done a phenomenal job of making an easy-to-use tool for getting started with reasonable defaults. If you're using Django though, you may not have the easiest time getting its static system and webpack to play well together.
A good chunk of this is applicable to any webpack-compiled frontend and Django, but we'll focus specifically on the steps involved with Vue CLI.
As a quick heads up: this tutorial assumes you're creating your Vue project in a folder named frontend
inside of your Django project folder. If you want it named something else, or want it in a different folder, just update the paths accordingly.
If you haven't already, install Vue CLI with npm i -g @vue/cli
.
Run vue ui
and create a new project named frontend
in your Django project folder. As far as presets and features, you do you.
Open your Django app in your favorite editor so we can make some changes.
Delete the following folders/files from the frontend folder:
- public/
- .gitignore (you're hopefully already using git for Django)
- README.md
In the frontend folder, run npm i --save-dev webpack-bundle-tracker
.
Update your vue.config.js
file to look like this:
const BundleTracker = require('webpack-bundle-tracker')
// Change this to match the path to your files in production (could be S3, CloudFront, etc.)
const DEPLOYMENT_PATH = '/static/dist/'
module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? DEPLOYMENT_PATH : 'http://localhost:8080/',
outputDir: '../(name of Django app)/static/dist',
devServer: {
public: 'localhost:8080',
headers: {
'Access-Control-Allow-Origin': '*',
},
},
configureWebpack: {
plugins: [
new BundleTracker({ path: __dirname, filename: 'webpack-stats.json' }),
],
},
}
Install django-webpack-loader
using pip.
In settings.py
add WEBPACK_LOADER
under your static settings:
STATIC_URL = '/static/'
WEBPACK_LOADER = {
'DEFAULT': {
'STATS_FILE': os.path.join(BASE_DIR, 'frontend', 'webpack-stats.json'),
}
}
Also be sure to add webpack_loader
to your list of INSTALLED_APPS
.
Almost there! Add this to the bottom of your body
tag:
{% render_bundle "chunk-vendors" %}
{% render_bundle "app" %}
You can now run npm run dev
to compile your app with hot module replacement, or npm run build
to create a production build.
You'll probably want to add these lines to your .gitignore
:
node_modules/
dist/
package-lock.json
webpack-stats.json
Alternative approach that does not need any plugins. (Not advocating against the approach described here, which has its advantages, I only wanted to explore a plugin-less alternative).