Reload plugin when using `jekyll serve` - ruby

I'm developing a Jekyll plugin. When I run the jekyll serve command, site files are regenerated when I change any markdown, html, or plugin files, as expected. The problem I've found is that while markdown/HTML files are regenerated, the plugins themselves are not reloaded. I have to terminate jekyll serve and issue the command again for the plugin changes to go into effect. Is there a way to make it so that the plugins get reloaded automatically when changed?
This is for Jekyll 3.1.2.

Based on the suggestion from #DavidJacquel and the gist I found here, I used Gulp with this gulpfile
'use strict';
var gulp = require('gulp'),
express = require('express'),
spawn = require('child_process').spawn;
var jekyll_file = process.platform === 'win32' ? 'jekyll.bat' : 'jekyll';
gulp.task('jekyll', () => {
var jekyll = spawn(jekyll_file, ['build', '--incremental']);
var output = '';
jekyll.stdout.on('data', (t) => { output += t; });
jekyll.stderr.on('data', (t) => { output += t; });
jekyll.on('exit', (code) => {
if (code)
console.log(`Jekyll exited with code: ${code}\n${output}`);
else
console.log("Finished Jekyll build");
});
});
gulp.task('serve', () => {
var server = express();
server.use(express.static('_site/'));
server.listen(4000);
});
gulp.task('watch', () => {
gulp.watch(['**/*.html', '**/*.md', '_plugins/*.rb', '!_site/**/*'], ['jekyll']);
});
gulp.task('default', ['jekyll', 'serve', 'watch']);
to get the desired effect. Also created issue here.

Related

How to add jekyll build command in gulp watch task?

I need to run jekyll build during gulp watch task and I did that as per the following code.
var gulp = require('gulp-help')(require('gulp')),
sass = require('gulp-sass');
gulp.task('sass', function(){
return gulp.src(sassFiles)
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest(cssDest));
});
gulp.task('jekyll-build', function (done) {
return cp.spawn(jekyll, ['build'], {stdio: 'inherit'})
.on('close', done);
});
gulp.task('default', ['sass'], function(){
gulp.watch(['_includes/**/*.js', '_includes/**/*._', 'assets/styles/**/*.scss'], ['jekyll-build', 'sass']);
});
When I make some changes in any file and try to save at once, command runs in terminal but it is not getting reflected in UI. I need to save twice or thrice to get the changes reflected. Not sure what's the issue or whether its the issue of the gulp watch code added here. Any help is appreciated.
When you say the changes are not reflected do you mean the browser is not refreshing?
The line to launch jekyll build is different for mac vs Windows, your looks like it is for a Mac, on Windows I use jekyll.bat on this line (jekyll, ['build'].
In your watch step you are not watching very much. Rather than try to tell gulp to watch every different thing I do the opposite and tell gulp to watch everything **/*.* and then tell it what not to watch like !_site/**/*. This also lets you watch the config file for changes.
Also, it doesn't look like you are live-reloading with browser sync, that is half the fun of using gulp with jekyll (other half is having gulp do sass processing as it is much faster than jekyll).
Here is a gulp file that I use and a link to a write up I did about it:
https://rdyar.github.io/2017/10/01/speed-up-jekyll-by-using-gulp-for-sass-and-other-assets/
var gulp = require('gulp');
var browserSync = require('browser-sync');
var cp = require('child_process');
var sass = require('gulp-sass');
var postcss = require('gulp-postcss');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('autoprefixer');
var watch = require('gulp-watch');
var uglify = require('gulp-uglify');
var cssnano = require('cssnano');
var imagemin = require('gulp-imagemin');
var htmlhint = require("gulp-htmlhint");
var messages = {
jekyllBuild: '<span style="color: grey">Running:</span> $ jekyll build'
};
// Gulp as asset manager for jekyll. Please note that the assets folder is never cleaned
//so you might want to manually delete the _site/assets folder once in a while.
// this is because gulp will move files from the assets directory to _site/assets,
// but it will not remove them from _site/assets if you remove them from assets.
/**
* Build the Jekyll Site - for windos. If you are on a Mac/linux change jekyll.bat to just jekyll
*/
gulp.task('jekyll-build', function (done) {
browserSync.notify(messages.jekyllBuild);
return cp.spawn('jekyll.bat', ['build'], {stdio: 'inherit'})
.on('close', done);
});
/**
* Rebuild Jekyll & do page reload when watched files change
*/
gulp.task('jekyll-rebuild', ['jekyll-build'], function () {
browserSync.reload();
});
/**
* Wait for jekyll-build, then launch the Server
*/
gulp.task('serve', ['jekyll-build'], function() {
browserSync.init({
server: "_site/"
});
});
/**
* Watch jekyll source files for changes, don't watch assets
*/
gulp.task('watch', function () {
gulp.watch(['**/*.*', '!_site/**/*','!_assets/**/*','!node_modules/**/*','!.sass-cache/**/*' ], ['jekyll-rebuild']);
});
//watch just the sass files - no need to rebuild jekyll
gulp.task('watch-sass', ['sass-rebuild'], function() {
gulp.watch(['_assets/sass/**/*.scss'], ['sass-rebuild']);
});
// watch just the js files
gulp.task('watch-js', ['js-rebuild'], function() {
gulp.watch(['_assets/js/**/*.js'], ['js-rebuild']);
});
// watch just the image files
gulp.task('watch-images', ['images-rebuild'], function() {
gulp.watch(['_assets/img/**/*.*'], ['images-rebuild']);
});
//if sass files change just rebuild them with gulp-sass and what not
gulp.task('sass-rebuild', function() {
var plugins = [
autoprefixer({browsers: ['last 2 version']}),
cssnano()
];
return gulp.src('_assets/sass/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(sourcemaps.init())
.pipe(postcss(plugins))
.pipe(sourcemaps.write('.'))
.pipe( gulp.dest('_site/assets/css/') )
.pipe(browserSync.reload({
stream: true
}))
});
gulp.task('js-rebuild', function(cb) {
return gulp.src('_assets/js/**/*.js')
.pipe(uglify())
.pipe( gulp.dest('_site/assets/js/') )
.pipe(browserSync.reload({
stream: true
}))
});
gulp.task('images-rebuild', function(cb) {
return gulp.src('_assets/img/**/*.*')
.pipe( gulp.dest('_site/assets/img/') )
.pipe(browserSync.reload({
stream: true
}))
});
/**
* Default task, running just `gulp` will
* compile the jekyll site, launch BrowserSync & watch files.
*/
gulp.task('default', ['serve', 'watch','watch-sass','watch-js','watch-images']);
//build and deploy stuff
gulp.task('imagemin', function() {
console.log('Minimizing images in source!!');
return gulp.src('_assets/img/**/*')
.pipe(imagemin())
.pipe(gulp.dest(function (file) {
return file.base;
}));
});
gulp.task('w3', function() {
gulp.src("_site/**/*.html")
.pipe(htmlhint())
.pipe(htmlhint.reporter())
})
// validate from the command line instead, works better
// npm install htmlhint -g
// htmlhint _site/**/*.html

ASP.Net Core + Angular 2 + SystemJS: typescript transpilation

I am using Visual Studio 2015 Update 3 to create a ASP.Net core application that runs an angular 2 application. I am using SystemJs for configuration that I picked from one of the sites and it has this line of code with the comment.
// DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
transpiler: 'typescript',
I understand the reason for the comment. My application is currently slow.
I'd like to know what are the other options available to ensure that the transpilation does not happen in the browser? How do I pre-transpile the code and load directly from the output location?
This usually means that ts files are sent to browser and transpiled there instead of happening on server side and js code to be sent and executed on client side.
Since you are using gulp you can create a task to transpile the typescript files and bundle them. You can use "gulp-typescript": "^2.5.0" package to achieve this.
However you need to setup your config first (I've just copy pasted the config from their repo):
'use strict';
var GulpConfig = (function () {
function gulpConfig() {
//Got tired of scrolling through all the comments so removed them
//Don't hurt me AC :-)
this.source = './src/';
this.sourceApp = this.source + 'app/';
this.tsOutputPath = this.source + '/js';
this.allJavaScript = [this.source + '/js/**/*.js'];
this.allTypeScript = this.sourceApp + '/**/*.ts';
this.typings = './typings/';
this.libraryTypeScriptDefinitions = './typings/main/**/*.ts';
}
return gulpConfig;
})();
module.exports = GulpConfig;
Then you need to setup the tasks, easiest way just to copy paste the already setup tasks from their repo again:
'use strict';
var gulp = require('gulp'),
debug = require('gulp-debug'),
inject = require('gulp-inject'),
tsc = require('gulp-typescript'),
tslint = require('gulp-tslint'),
sourcemaps = require('gulp-sourcemaps'),
del = require('del'),
Config = require('./gulpfile.config'),
tsProject = tsc.createProject('tsconfig.json'),
browserSync = require('browser-sync'),
superstatic = require( 'superstatic' );
var config = new Config();
/**
* Generates the app.d.ts references file dynamically from all application *.ts files.
*/
// gulp.task('gen-ts-refs', function () {
// var target = gulp.src(config.appTypeScriptReferences);
// var sources = gulp.src([config.allTypeScript], {read: false});
// return target.pipe(inject(sources, {
// starttag: '//{',
// endtag: '//}',
// transform: function (filepath) {
// return '/// <reference path="../..' + filepath + '" />';
// }
// })).pipe(gulp.dest(config.typings));
// });
/**
* Lint all custom TypeScript files.
*/
gulp.task('ts-lint', function () {
return gulp.src(config.allTypeScript).pipe(tslint()).pipe(tslint.report('prose'));
});
/**
* Compile TypeScript and include references to library and app .d.ts files.
*/
gulp.task('compile-ts', function () {
var sourceTsFiles = [config.allTypeScript, //path to typescript files
config.libraryTypeScriptDefinitions]; //reference to library .d.ts files
var tsResult = gulp.src(sourceTsFiles)
.pipe(sourcemaps.init())
.pipe(tsc(tsProject));
tsResult.dts.pipe(gulp.dest(config.tsOutputPath));
return tsResult.js
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(config.tsOutputPath));
});
/**
* Remove all generated JavaScript files from TypeScript compilation.
*/
gulp.task('clean-ts', function (cb) {
var typeScriptGenFiles = [
config.tsOutputPath +'/**/*.js', // path to all JS files auto gen'd by editor
config.tsOutputPath +'/**/*.js.map', // path to all sourcemap files auto gen'd by editor
'!' + config.tsOutputPath + '/lib'
];
// delete the files
del(typeScriptGenFiles, cb);
});
gulp.task('watch', function() {
gulp.watch([config.allTypeScript], ['ts-lint', 'compile-ts']);
});
gulp.task('serve', ['compile-ts', 'watch'], function() {
process.stdout.write('Starting browserSync and superstatic...\n');
browserSync({
port: 3000,
files: ['index.html', '**/*.js'],
injectChanges: true,
logFileChanges: false,
logLevel: 'silent',
logPrefix: 'angularin20typescript',
notify: true,
reloadDelay: 0,
server: {
baseDir: './src',
middleware: superstatic({ debug: false})
}
});
});
gulp.task('default', ['ts-lint', 'compile-ts']);
This creates the following Gulp tasks:
gen-ts-refs: Adds all of your TypeScript file paths into a file named typescriptApp.d.ts. This file will be used to support code help in some editors as well as aid with compilation of TypeScript files.
ts-lint: Runs a “linting” task to ensure that your code follows specific guidelines defined in the tsline.js file (you can skip this if you like).
compile-ts: Compiles TypeScript to JavaScript and generates source map files used for debugging TypeScript code in browsers such as Chrome.
clean-ts: Used to remove all generated JavaScript files and source map files.
watch: Watches the folder where your TypeScript code lives and triggers the ts-lint, compile-ts, and gen-ts-refs tasks as files changes are detected.
default: The default Grunt task that will trigger the other tasks to run. This task can be run by typing gulp at the command-line when you’re within the typescriptDemo folder.
Note:
You need to change the folders based your file structure but the gist of it is that you need those TypeScript files to be compiled and sent to browser as plain JavaScript.

Gulp not being invoked on project build

According to step 5 of this tutorial, when I build my project Gulp should copy the contents of my node_modules folder into the wwwroot.
It's not doing it though. I've tried ticking the boxes in the project properties page (no idea if that should make a different or not though).
The gulpfile.js looks like so:
var ts = require('gulp-typescript');
var gulp = require('gulp');
var clean = require('gulp-clean');
var destPath = './wwwroot/libs/';
// Delete the dist directory
gulp.task('clean', function () {
return gulp.src(destPath)
.pipe(clean());
});
gulp.task("scriptsNStyles", () => {
gulp.src([
'es6-shim/es6-shim.min.js',
'systemjs/dist/system-polyfills.js',
'systemjs/dist/system.src.js',
'reflect-metadata/Reflect.js',
'rxjs/**',
'zone.js/dist/**',
'#angular/**',
'jquery/dist/jquery.*js',
'bootstrap/dist/js/bootstrap.*js',
], {
cwd: "node_modules/**"
})
.pipe(gulp.dest("./wwwroot/libs"));
gulp.src([
'node_modules/bootstrap/dist/css/bootstrap.css'
]).pipe(gulp.dest('./wwwroot/libs/css'));
});
var tsProject = ts.createProject('scripts/tsconfig.json');
gulp.task('ts', function (done) {
//var tsResult = tsProject.src()
var tsResult = gulp.src([
"scripts/*.ts"
])
.pipe(ts(tsProject), undefined, ts.reporter.fullReporter());
return tsResult.js.pipe(gulp.dest('./wwwroot/appScripts'));
});
gulp.task('watch', ['watch.ts']);
gulp.task('watch.ts', ['ts'], function () {
return gulp.watch('scripts/*.ts', ['ts']);
});
gulp.task('default', ['scriptsNStyles', 'watch']);
To be honest, I'm struggling to debug as I don't know what bit should be making Gulp be invoked on build.
Any clarification would be very helpful.
Cheers
There seems to be a step missing from the tutorial. You need to set up a binding to run your Gulp task when the project is built.
To do this open the Task Runner Explorer window (View -> Other Windows -> Task Runner Explorer). This should list all the Gulp tasks in your gulpfile.js. Right click the one you want to run upon build (probably default) and select Bindings -> After Build. You can also run the tasks manually by right clicking and selecting 'Run'.

Gulp upload ftp after watch finished

Here's my gulp file. It should compile scss and upload file after change. It uploads, but not always. What am I doing wrong?
var gulp = require('gulp'),
watch = require('gulp-watch'),
gutil = require( 'gulp-util' ),
sass = require('gulp-sass'),
ftp = require( 'vinyl-ftp' );
gulp.task( 'deploy', function () {
var conn = ftp.create( {
host: 'host',
user: 'user#host',
password: 'pass',
parallel: 10,
log: gutil.log
} );
var globs = [
'src/**',
'css/**',
'build/**',
'js/**',
'fonts/**',
'index.html'
];
// using base = '.' will transfer everything to /public_html correctly
// turn off buffering in gulp.src for best performance
return gulp.src( globs, { base: '.', buffer: false } )
.pipe( conn.newer( '/test' ) ) // only upload newer files
.pipe( conn.dest( '/test' ) );
} );
gulp.task('css', function () {
return gulp.src('scss/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('css'))
});
gulp.task('watch', function (){
gulp.watch('scss/**/*.scss', ['css', 'deploy']);
});
This line doesn't do what you think it does:
gulp.watch('scss/**/*.scss', ['css', 'deploy']);
This does not run the css task followed by the deploy task. Gulp executes all tasks with maximum concurrency unless you tell it otherwise.
That means your css and deploy tasks both start running immediately whenever a .scss file is changed. Depending on whether your css task finishes compiling your .scss files before your deploy task starts transmitting them, this might work or it might not.
You need to tell gulp to execute the deploy task only after the css task has finished:
gulp.task( 'deploy', ['css'], function () {
//...
});

Gulp, Compass and LiveReload - no style injection, page always reloads

Everything is almost working, compass is compiling the CSS and a few other tasks are running to minify, rename, rev etc. The problem is that when a style change occurs LiveReload is reloading the page instead of injecting the style. If I switch back to compass watch then style injection occurs. Is it possible to have style injection with Gulp, Compass and LiveReload? I hope so because if not I will have to run compass watch in 1 terminal and gulp in another which seems a bit clunky. Here is the relevant code from the gulpfile.js
var gulp = require('gulp'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
compass = require('gulp-compass'),
minifyCSS = require('gulp-minify-css'),
rev = require('gulp-rev'),
rename = require('gulp-rename'),
clean = require('gulp-clean'),
lr = require('tiny-lr'),
server = lr(),
livereload = require('gulp-livereload');
gulp.task('compass', function() {
gulp.src('./static/scss/*.scss')
.pipe(compass({
css: 'static/css',
sass: 'static/scss',
image: 'static/images',
font: 'static/fonts',
javascript: 'static/js',
comments: false,
style: 'expanded',
bundle_exec: true,
require: ['wegowise_styles/compass']
}))
.on('error', function(err) {})
.pipe(gulp.dest('./static/css/'))
.pipe(livereload(server))
.pipe(minifyCSS())
.pipe(rename({suffix: '.min'}))
.pipe(rev())
.pipe(gulp.dest('./static/production/'))
.pipe(rev.manifest())
.pipe(rename('css-manifest.json'))
.pipe(gulp.dest('./static/production/'));
});
gulp.task('clean', function() {
return gulp.src(['static/production'], {read: false})
.pipe(clean());
});
gulp.task('watch', function() {
gulp.watch('static/scss/**/*.scss', ['compass']);
gulp.watch('static/js/**/*.js', ['scripts']);
});
gulp.task('default', ['clean', 'watch']);
ps. I am using the LiveReload chrome extension
Yes, it is possible. I haven't seem in your code (maybe because you removed the rest of the file) when you start tiny-lr, i.e.:
var gutil = require('gulp-util');
gulp.task('tiny', function(next) {
server.listen(35729, function() {
gutil.log('Server listening on port: ', gutil.colors.magenta(port));
next();
});
});
// add as a dependency in your watch task
gulp.task('watch', ['tiny'], function() {
gulp.watch('static/scss/**/*.scss', ['compass']);
gulp.watch('static/js/**/*.js', ['scripts']);
});
The error might be related to the scripts task as well, so maybe include it in the question so we can take a look. Maybe, finally, there is some other task causing the issue.
In order to be sure, I just created a test here, and created a index.html file inside the static folder, pointing to css/file.css.
Created a simple static/scss/file.scss with a body background-color. I've used the same code snippet you provided for the rest of the gulpfile.
Also created a node-static server and served all files under static/ folder.
At the end, is there any other automated task involved in the building process?

Resources