How to use Gulp Browsersync with Django?
First time using Gulp and I'm following a couple of tutorials that don't seem to be working quite right for me. I have a real basic project and I just want to learn how to use Gulp for standard things like JavaScript/CSS minification, image reduction, and browser sync.
When I run my watch task with Browsersync, it goes to the right URL of localhost:8000
, but it shows Cannot GET /
instead of rendering my page. How do I fix this so I can use Browsersync with Django?
File directory:
gulpfile.js
:
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
gulp.task('sass', function() {
return gulp.src('polls/static/polls/scss/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('polls/static/polls/css'))
.pipe(browserSync.reload({
stream: true
}))
});
gulp.task('browserSync', function() {
browserSync.init({
server: "mysite",
port: 8000
});
});
gulp.task('watch', ['browserSync', 'sass'], function() {
gulp.watch('polls/static/polls/scss/**/*.scss', ['sass']);
})
Solution 1:
Just had to make another task called runserver
which runs in the cmd python manage.py runserver
. Put the task as one of the dependencies for Browsersync, set the proxy and port, and I was set to go.
var exec = require('child_process').exec
didn't require any extra npm install
. I think it's automatically built in.
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
var exec = require('child_process').exec;
gulp.task('sass', function() {
return gulp.src('polls/static/polls/scss/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('polls/static/polls/css'))
.pipe(browserSync.reload({
stream: true
}))
});
gulp.task('runserver', function() {
var proc = exec('python manage.py runserver')
})
gulp.task('browserSync', ['runserver'], function() {
browserSync.init({
notify: false,
port: 8000,
proxy: 'localhost:8000'
})
});
gulp.task('watch', ['browserSync', 'sass'], function() {
gulp.watch('polls/static/polls/scss/**/*.scss', ['sass']);
gulp.watch('polls/static/polls/scripts/**/*.js', browserSync.reload);
gulp.watch('polls/templates/**/*.html', browserSync.reload);
})
Solution 2:
Using Gulp 4, here is a copy of my code:
const gulp = require('gulp');
const browserSync = require('browser-sync').create();
const exec = require('child_process').exec;
gulp.task('runserver', function() {
var proc = exec('python manage.py runserver');
return new Promise(function(resolve, reject) {
console.log("HTTP Server Started");
resolve();
});
})
gulp.task('browserSync', gulp.series('runserver'), function() {
browserSync.init({
notify: false,
port: 8000,
proxy: 'localhost:8000'
});
});
gulp.task('watch', gulp.series('browserSync'), function() {
gulp.watch('polls/static/polls/scripts/**/*.js', browserSync.reload);
gulp.watch('polls/templates/**/*.html', browserSync.reload);
})