I want to use a combination of VScode + Gulp + Electron to build an application. A nice feature of the development workflow would be to add an live reload task to my Gulp watch task, to reload the Electron application on every change.
Any Idea how to achieve this?
Your help is highly appreciated.
I was able to achieve this with the gulp-livereload plugin. Here is the code to livereload CSS ONLY. It's the same for everything else though.
var gulp = require ('gulp'),
run = require('gulp-run'),
livereload = require('gulp-livereload'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
rename = require('gulp-rename'),
minifycss = require('gulp-minify-css'),
jshint = require('gulp-jshint'),
autoprefixer = require('gulp-autoprefixer'),
rimraf = require('gulp-rimraf');
var cssSources = [
'app/components/css/main.css',
];
gulp.task('css', function(){
gulp.src(cssSources)
.pipe(concat('main.css'))
.pipe(autoprefixer({browsers: ['last 2 versions', 'ie 10']}))
.pipe(gulp.dest('app/public/styles'))
.pipe(rename({suffix: '.min'}))
.pipe(minifycss())
.pipe(gulp.dest('app/public/styles'))
.pipe(livereload());
})
gulp.task('watch', function(){
livereload.listen();
gulp.watch(cssSources, ['css'])
})
gulp.task('run', ['build'], function() {
return run('electron .').exec();
});
gulp.task('default', ['watch', 'run']);
Livereload in a desktop application is awesome.
Make sure you add
<script src="http://localhost:35729/livereload.js"></script>
to your index.html
Even though this has already been answered/accepted, worth mentioning I've also managed to get it working with electron-connect
There is also a way to do this using the gulp-webserver (The reason I ran across this post), and does not require the gulp-livereload. Ignore the react-generator which is a separate task that does my react transforms. Needless to say, this task starts the webserver, watches for changes, runs the generator, and then reloads on those changes.
var gulp = require('gulp'),
electron = require('electron-prebuilt'),
webserver = require('gulp-webserver'),
gulp.task(
'run',
['react-generator'], // Secondary task, not needed for live-reloading
function () {
gulp.watch('./app/react/*.jsx', ['react-generator']);
gulp.src('app')
.pipe(webserver({
port: 8123,
fallback: "index.html",
host: "localhost",
livereload: {
enable: true,
filter: function(fileName) {
if (fileName.match(/.map$/)) {
return false;
} else {
return true;
}
}
},
}));
});
As noted in the previous answer, you will need to add the following to your index file, or it will act like it doesn't work for Electron, but does for browsers.
<script src="http://localhost:35729/livereload.js"></script>
Not specifically with Gulp, but there is an easy Electron plugin meant just for that (reloading an application after a change has been made): electron-reload
Just add the package:
$ npm install electron-reload --save-dev
And add the following line to the top of the /main.js file:
require('electron-reload')(__dirname)
The simplest way I've found is using electron-reloader, after installation, just paste the following code at the top of the app entry file (usually named main.js), and you're all set:
const { app } = require('electron')
app.isPackaged || require('electron-reloader')(module)
Related
I'm setting up a project with TailwindCSS. I'm trying to set up my automation with Gulp, but I'm running into an issue with the HTML reloading. Everything seems to work perfectly fine when I run Gulp, it minifies and cleans my CSS, concats and minifies my JS, etc., but when I try saving a class from Tailwind in my HTML, my BrowserSync in my Gulp file doesn't reload. My Gulpfile is below.
var gulp = require('gulp')
autoprefixer = require('gulp-autoprefixer')
cleanCSS = require('gulp-clean-css')
rename = require('gulp-rename')
purgecss = require('gulp-purgecss')
concat = require('gulp-concat')
uglify = require('gulp-uglify')
replace = require('gulp-replace')
postcss = require('gulp-postcss')
tailwindcss = require('tailwindcss')
browserSync = require('browser-sync').create();
// CSS TASK
function css(){
return gulp.src('./src/css/app.css')
.pipe(postcss([
require('tailwindcss'),
require('autoprefixer'),
]))
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(rename(function(path){
path.extname = ".min.css"
}))
.pipe(
purgecss({
content: ['./*.html']
})
)
.pipe(gulp.dest('./dist/css'))
.pipe(browserSync.stream());
}
// JS TASK
function js(){
return gulp.src('./src/js/**/*.js')
.pipe(concat('main.min.js'))
.pipe(uglify())
.pipe(gulp.dest('./dist/js'))
.pipe(browserSync.stream());
}
// CACHEBUSTING TASK
const cbString = new Date().getTime();
function cacheBustTask(){
return src(['index.html'])
.pipe(replace(/cb=\d+/g, 'cb=' + cbString))
.pipe(dest('.')
);
}
// BROWSERSYNC
function serve(){
browserSync.init({
server: {
baseDir: './'
}
})
}
// WATCH
gulp.watch('./src/css/**/*.css', css);
gulp.watch('./src/js/**/*.js', js);
gulp.watch('./*.html').on('change', browserSync.reload);
// EXPORT IN ORDER
exports.default = gulp.parallel(css, js, serve);
I don't think you need ./ in your gulpfile, also I would suggest not having tailwindcss run as part of your css on file change, watch gulp task.
postcss([
require('tailwindcss'),
require('autoprefixer'),
])
I'd suggest placing it in it's own gulp task, that you run whenever you update tailwindcss.
I have had a similar problem and solved it by tweaking the watchers in my gulpfile.
In your case, the line that configures the HTML watcher looks like this:
gulp.watch('./*.html').on('change', browserSync.reload);
When you save a HTML file, this watcher refreshes your browser window. But it doesn't do anything else.
In order for Tailwind to work properly, you also need to trigger JIT compilation of the classes it detects in your HTML code. If you pass your CSS task as a callback to the watcher, the problem could resolve.
So, instead of the above, try:
gulp.watch('./*.html', css).on('change', browserSync.reload);
I have a problem with the linting and live reloading in my gulp file. They take to much time to finish.
Here is my gulp file, what do I do wrong :
'use strict';
console.time("Loading plugins"); //start measuring
var gulp = require('gulp');
var connect = require('gulp-connect');
var open = require('gulp-open');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var concat = require('gulp-concat');
var babelify = require('babelify');
var sass = require('gulp-sass');
var merge = require('merge-stream'); // Merge all styles (css, sass and less) in one big bundle
var lint = require("gulp-eslint");
var config = {
port: 8001,
devBaseUrl: 'http://localhost',
paths: {
html: "./src/*.html",
externals: "./src/assets/externals/*.js",
js: "./src/**/*.js",
images: './src/assets/images/**/*',
fonts: './src/assets/css/fonts/*',
css: [
"./src/assets/css/*",
],
sass: './src/assets/css/*.scss',
dist: "./dist",
mainJS: "./src/main.js"
}
};
gulp.task('connect', ['watch'], function () {
connect.server({
root: ['dist'],
port: config.port,
base: config.devBaseUrl,
livereload: true,
fallback: './dist/index.html'
})
});
gulp.task('open', ['connect'], function () {
gulp.src('dist/index.html')
.pipe(open({uri: config.devBaseUrl + ":" + config.port + "/"}));
});
gulp.task('html', function () {
gulp.src(config.paths.html)
.pipe(gulp.dest(config.paths.dist))
.pipe(connect.reload());
});
gulp.task('externals', function () {
gulp.src(config.paths.externals)
.on('error', console.error.bind(console))
.pipe(concat('external.js'))
.pipe(gulp.dest(config.paths.dist + '/externals'))
.pipe(connect.reload());
});
gulp.task('js', function () {
browserify(config.paths.mainJS)
.transform('babelify', {presets: ['es2015', 'react']})
.bundle()
.on('error', console.error.bind(console))
.pipe(source('bundle.js'))
.pipe(gulp.dest(config.paths.dist + '/scripts'))
.pipe(connect.reload());
});
gulp.task('images', function () {
gulp.src(config.paths.images)
.pipe(gulp.dest(config.paths.dist + '/images'));
});
gulp.task('styles', function () {
gulp.src(config.paths.css)
.pipe(sass())
.pipe(concat('bundle.css'))
.pipe(gulp.dest(config.paths.dist + '/css'))
.pipe(connect.reload());
});
gulp.task('fonts', function () {
gulp.src(config.paths.fonts)
.pipe(gulp.dest(config.paths.dist + '/css/fonts'));
});
gulp.task('lint', function () {
return gulp.src(config.paths.js)
.pipe(lint())
.pipe(lint.format());
});
gulp.task('watch', function () {
gulp.watch(config.paths.js, ['js', 'lint']);
gulp.watch(config.paths.css, ['styles']);
});
console.timeEnd('Loading plugins');
gulp.task('default', ['js', 'styles', 'lint', 'open', 'watch']);
The lint takes almost 20s to finish and liverolading takes 5-6s to refresh the browser after I make some changes.
Any advice?
Gulp ESLint plugin is generally very slow. I compared it to Grunt at some point (a while back) and it was about 5-10 times slower. Don't know why.
Make sure you are running latest version of ESLint and also that you don't have node_modules directory under your src folder. If you do, you can run eslint with --debug flag to make sure that ESLint is not linting files in your node_modules directory. If for some reason it does, add .eslintignore file and specify everything that you don't want to lint there.
In general, if you want instant feedback while coding, I would suggest looking into editor integrations. Pretty much every editor out there has ESLint plugin at this point. They show you errors directly in the window you are writing your code in.
We've recently come across the same issue on my team. The best workaround was to run ESLint only on the modified files, instead of all js files.
We use nodemon to watch for changed files, though gulp-watch has the same idea.
See the change event on gulp-watch.
Then you'd just run a lint function on the changed file.
You may need to resolve the relative file path.
gulp.watch(config.paths.js, ['js'])
.on('change', lintFile);
const lintFile = (file) => {
return gulp.src(file)
.pipe(eslint());
};
Is it necessary to check you code while developing?
We use another approach:
1)Do not check code while developing, because it is long, also it sometimes doesn't allow to create "fast" mock for something while debugging.
2)Check style only before commit. If something is wrong, fix style and check everything works. Also CI system could control your commits.
So, my suggestion is to remove lint from watch task.
I'm trying to set up gulp to run livereload using MAMP. Here is my gulpfile:
'use strict';
var gulp = require('gulp');
var del = require('del');
var sass = require('gulp-sass');
var livereload = require('gulp-livereload');
var paths = {
elements: ['elements/**/*']
};
gulp.task('clear:cache', function () {
return del(['core/cache/**/*']).then(function(){
livereload();
console.log('live reload called');
}).catch(function(){
livereload();
});
});
gulp.task('sass', function () {
console.log('sassy live reload');
return gulp.src('assets/styles/scss/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('assets/styles/css'))
.pipe(livereload());
});
gulp.task('sass:watch', function () {
gulp.watch('assets/styles/scss/*.scss', ['sass']);
});
// Rerun the task when a file changes
gulp.task('watch', function() {
livereload.listen({port:8888,host:"localhost",start:true, reloadPage:"index.php"});
gulp.watch(paths.elements, ['clear:cache', 'sass:watch']);
});
// The default task (called when you run `gulp` from cli)
gulp.task('default', ['sass:watch','clear:cache','watch']);
As you can see, the gulpfile is supposed to clear the cache and reload the browser whenever changes are made to files in the elements directory, and compile the sass and reload the browser whenever any scss files are changed. The cache clearing and sass compiling work fine, and both spit out the console.log messages in their respective functions.
Where I'm having trouble is getting livereload to reload the browser. I know that livereload is working but not targeting the browser at all, in fact, because I get messages in my terminal like /Applications/MAMP/htdocs/assets/styles/css/style.css reloaded.
By default the LiveReload extensions listens on port 35729. To use a different port, like 8888 in your example, you have to override the default. More infos can be found here http://feedback.livereload.com/knowledgebase/articles/195869-how-to-change-the-port-number-livereload-listens-o
You can use Live Reload Browser Page
Live Reload Browser Page
GitHub live-reload-bp
Works with NodeJs, Grunt, Gulp, WebPack. You can use any IDE if it has a function to autosave a file after editing
I have been playing with gulp and babel for the past few days. I am getting a solid grasp of setting up babel with gulp through tutorials. I've noticed that the newer the tutorial the more changes that develop.
Here is one way I was able to set up es6 to es5 with a transpiler.
var gulp = require('gulp');
var babel = require('gulp-babel');
gulp.task('es6to5', function () {
return gulp.src('js/src/app.js')
.pipe(babel())
.pipe(gulp.dest('dist'));
});
However, I do not want to rerun gulp each time, and I want the dist/ folder to update on each save.
I added browser-sync and delete.
var gulp = require('gulp');
var babel = require('gulp-babel');
var browserSync = require('browser-sync');
var del = require('del');
gulp.task('clean:dist', function() {
return del([
'dist/app.js'
]);
});
gulp.task('es6to5', function () {
return gulp.src('js/src/app.js')
.pipe(babel())
.pipe(gulp.dest('dist'));
});
gulp.task("browserSync", function() {
browserSync({
server: {
baseDir: './dist'
}
});
});
gulp.task("copyIndex", ['clean:dist'], function() {
gulp.src("src/index.html")
.pipe(gulp.dest('./dist'))
.pipe(browserSync.reload({stream: true}));
});
gulp.task('watchFiles', function() {
gulp.watch('src/index.html', ['copyIndex']);
gulp.watch('src/**/*.js', ['babelIt']);
});
gulp.task('default', ['clean:dist', 'es6to5','browserSync','watchFiles']);
I set up a default that will clean out the dist folder then run es6to5. Afterwards I want it to sync and update. I called watchFiles last.
However, I am no longer getting updated js files. The files in the dist folder Are not compiling to es5 and everything is going to a 404.
The task
copyIndex seems to be the problem but I am not sure how to fix it or if it is the only problem. Any direction helps.
You have a typo.
It should be gulp.watch('src/**/*.js', ['es6to5']);, not gulp.watch('src/**/*.js', ['babelIt']);
Anyway i suggest to use gulp-watch instead of the built-in watch function. It has several advantages, mainly it recompile on new file creation.
after reading alot and trying to make my own gulpfile.js I figured out how to make it compile my "scss" to a "css", the problem is that my browser-sync doesn't work because I need a proxy (because im using .php not .html), If I write this on CMD: "browser-sync start --proxy localhost:8080/app" I can see my files, but I need it to sync every time I modify something on my "scss". All I need now is to implement the proxy thing on it and reloads everytime I save/modify the ".scss", this is my currently gulpfile.js :
var gulp = require('gulp');
var httpProxy = require('http-proxy');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var paths = {
scss: '.sass/*.scss'
};
gulp.task('sass', function () {
gulp.src('scss/style.scss')
.pipe(sass({
includePaths: ['scss']
}))
.pipe(gulp.dest('css'));
});
gulp.task('browser-sync', function() {
browserSync.init(["css/*.css", "js/*.js"], {
server: {
baseDir: "./"
}
});
});
gulp.task('watch', ['sass', 'browser-sync'], function () {
gulp.watch(["scss/*.scss", "scss/base/*.scss", "scss/sections/*.scss", "scss/style/*.scss"], ['sass']);
});
This gulpfile.js is watching my "scss/syle.scss" and updates my "css/style.css" everytime I modify the scss file.
Have you taken a look at the browserSync options? This should give you a pretty good idea on how to set it up. It doesn't seem like you implemented it in the gulpfile you provided.