Start hexo to generate a watch in a gulpfile.js? - gulp

I have the following gulpfile.js
var gulp = require('gulp'),
browserSync = require('browser-sync'),
sass = require('gulp-sass'),
bower = require('gulp-bower'),
notify = require('gulp-notify'),
reload = browserSync.reload,
bs = require("browser-sync").create(),
Hexo = require('hexo'),
hexo = new Hexo(process.cwd(), {});
var src = {
scss: './scss/',
css: './source/css',
ejs: 'layout'
},
watchFiles = [
'./scss/*.scss',
'*/*.ejs'
];
// Static Server + watching scss/html files
gulp.task('serve', ['sass:watch'], function() {
// init starts the server
bs.init(watchFiles, {
server: {
baseDir: "../../public"
},
logLevel: "debug"
});
hexo.init();
hexo.call('generate', {}, function(){
console.log('Started Hexo Server');
})
});
How does one start hexo in a watch in a gulpfile?
The rest of the gulpfile is here:
https://github.com/chrisjlee/hexo-theme-zurb-foundation/blob/master/gulpfile.js
The hexo index file takes in arguments here; but i couldn't figure out the arguments;
https://github.com/hexojs/hexo/blob/master/lib/hexo/index.js

You can pass arguments in the second parameter. For example:
hexo.init().then(function(){
return hexo.call('generate', {watch: true});
}).catch(function(err){
console.log(err);
});

Related

how to add browser-sync in gulp-4

//Importing gulp files to variables
const { src , dest , watch , series , parallel } = require('gulp');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
const concat = require('gulp-concat');
const postcss = require('gulp-postcss');
const replace = require('gulp-replace');
const sass = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify');
const browserSync = require ('browser-sync').create();
// File path variables in my projects folder
const files = {
scsspath:'assets/scss/**/*.scss' ,
jspath:'assets/js/**/*.js'}
//Sass Task
function scssTask(){
return src(files.scsspath)
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(sourcemaps.write('.'))
.pipe(dest('assets/css'))
.pipe(browsersync.stream());}
//JsTask
function jsTask(){
return src(files.jspath)
.pipe(concat('all.js'))
.pipe(uglify())
.pipe(dest('assets/js')).pipe(browsersync.stream());}
//WatchTask
function watchTask(){
watch([files.scsspath , files.jspath], parallel(scssTask,jsTask));}
//DefaultTask
//I don't know how to use browser-sync in gulp-4
exports.default = series(parallel(scssTask,jsTask) , cashBustTask ,
watchTask,browsersync);
Create a separate task for browser-sync. Here's an example of how I've set this up:
const bs = require('browser-sync').create();
// Other inputs used with browser-sync
const { src, dest, watch } = require('gulp');
const sass = require('gulp-sass');
function browserSync() {
// Run serveSass function when starting the dev server to make sure the SCSS & dev CSS are the same
serveSass();
bs.init({
// Dev server will run at localhost:8080
port: 8080,
server: {
// I'm using 'src' as my base directory
baseDir: 'src',
},
});
// These watch for changes to files and reload in the browser
watch('src/*.html').on('change', bs.reload);
watch('src/scss/*.scss', serveSass);
watch('src/js/*.js').on('change', bs.reload);
}
// This compiles Sass when running browser-sync and reloads the CSS
function serveSass() {
// My dev Sass files are found in 'src/scss/'
return src('src/scss/*.scss')
.pipe(sass())
// My dev CSS files are found in 'src/css/'
.pipe(dest('src/css))
.pipe(bs.stream());
}
// Then I run 'gulp serve' in the terminal to start browser-sync and my dev server
exports.serve = browserSync;
My full Gulp setup is here if you want more context.
Quick solution:
Add a function to trigger BrowserSync:
function reload(){
browserSync.reload();
}
Modify your watchTask() function to:
function watchTask(){
browserSync.init({
server: { baseDir: "./dist" }
});
gulp.watch([files.scsspath , files.jspath], parallel(scssTask,jsTask,reload));
}
Modify your exports to:
exports.default = watchTask;
I found this guide to upgrade gulp 4, that explains that gulp.series or gulp.parallel needs to be used. Example:
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
gulp.task('browserSyncReload', gulp.series( function(done) {
browserSync.reload();
done();
}));
gulp.task('default', gulp.series( function(done) {
browserSync.init({
notify: false,
proxy: "127.0.0.1:5003/nl"
});
gulp.watch("app/templates/**/*.", gulp.series('browserSyncReload'));
gulp.watch("app/static/**/*.*", gulp.series('browserSyncReload'));
done();
}));

Gulp css styles are not updated

I have problem. Yestrday I had to update the Node.js kernel and now that I change something in the LESS file, there will be no css update. Gulpfile is the same as before the update. Could someone advise me what's wrong with my gulpfile script?
The HTML file update is OK.
//*********** IMPORTS *****************
var gulp = require('gulp'),
browserSync = require('browser-sync');
var postcss = require('gulp-postcss');
var less = require('gulp-less');
var watch = require('gulp-watch');
var livereload = require('gulp-livereload');
var autoprefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat-css');
var cssmin = require('gulp-cssmin');
/* BROWSERSYNC */
gulp.task('browserSync', function () {
var files = ['orient-spa/**'];
browserSync.init(files, {
server: {
baseDir: 'orient-spa/',
index: 'index.html'
},
logPrefix: 'OS01',
browser: ['chrome']
});
});
gulp.task('css', function () {
var processors = [
autoprefixer
];
return gulp.src('./orient-spa/skins/less/index-files.less')
.pipe(less())
.pipe(postcss(processors))
.pipe(gulp.dest('./orient-spa/skins/css/'))
.pipe(livereload());
});
gulp.task('watch', function() {
livereload.listen();
gulp.watch('./orient-spa/skins/less/*.less', ['css']);
gulp.watch('./orient-spa/skins/css/*.css', ['concatMinify']);
});
gulp.task('concatMinify', function () {
return gulp.src('./orient-spa/skins/css/*.css')
.pipe(concat("index.css"))
.pipe(cssmin())
.pipe(gulp.dest('./orient-spa/skins/css/compiled'))
.pipe(livereload());
});
gulp.task('default', ['browserSync', 'watch', 'css', 'concatMinify']);
Thanks for your advice :-)
I try this path, but problem remains.
Last version node.js was Node.js 7.2.1 (Node.js), now Node.js 9.8.0.
I attach an image to the console after changing 1 line in the LESS file.
Here I see that the set of commands does not call correctly. Or they are called repeatedly. Do not you see a mistake here, please?
Thanks for your advice

Bundling javascript files to watch with Gulp and Nodeman

I have the start and deploy tasks working the way I want them to but I am trying to figure out how to update public/js/bundle.js when I make a change in app.js so that it can be watched.
Here's what I got so far:
var gulp = require('gulp');
var streamify = require('gulp-streamify');
var uglify = require('gulp-uglify');
var transform = require('vinyl-source-stream');
var browserify = require('browserify');
var rename = require('gulp-rename');
var nodemon = require('gulp-nodemon');
var ios = browserify({
entries:['app.js']
});
const bundle = () => {
process.env.NODE_ENV = 'production';
ios.require('./app-ios.js', {expose:'appalias'})
.bundle()
.pipe(transform('bundle-ios.js'))
.pipe(gulp.dest('./public/js'))
.pipe(streamify(uglify()))
.pipe(rename('bundle-ios.min.js'))
.pipe(gulp.dest('./public/js'));
return ios;
}
const start = () => {
return nodemon({
script: 'server.js',
watch: ['server.js', 'public/js/*', 'public/index.html', 'public/css/*'],
ext: 'js html css',
env: { 'NODE_ENV': 'development' },
});
}
// Start local server and watch bundles.
gulp.task('start', start);
// Build minified versions for prod.
gulp.task('deploy', bundle);
The fix was to watch all the individual javascript component and model files and add a compile task to the start task.
// Bundle and minify for development, use development version of libraries.
const compile = () => {
process.env.NODE_ENV = 'development';
const bundleAndroidDev = ios.require('./app-ios.js', {expose:'appalias'})
.bundle()
.pipe(transform('bundle-ios.js'))
.pipe(gulp.dest('./public/js'));
return bundleIosDev;
}
// Start local server and watch for changes in compiled bundles.
const start = () => {
return nodemon({
script: 'server.js',
watch: ['server.js', 'apps/appName/components/*', 'apps/appName/models/*', 'public/index.html', 'public/css/*'],
ext: 'js html css',
tasks: ['compile'],
env: { 'NODE_ENV': 'development' }
});
}
// Compile bundle's on save.
gulp.task('compile', compile);

gulp browserify does not exit

Following is the code I inherited for gulp and browserify
'use strict';
var gulp = require('gulp'),
browserify = require('browserify'),
glob = require('glob'),
path = require('path'),
source = require('vinyl-source-stream'),
notifier = require('node-notifier'),
_ = require('underscore'),
watchify = require('watchify'),
jshint = require('gulp-jshint'),
chalk = require('chalk'),
del = require('del'),
webserver = require('gulp-webserver'),
cleanCSS = require('gulp-clean-css'),
babelify = require("babelify"),
jasmine = require('gulp-jasmine');
var browserifyables = './web-app/**/*-browserify.js';
function logError(error){
/* jshint validthis: true */
notifier.notify({
title: 'Browserify compilation error',
message: error.toString()
});
console.error(chalk.red(error.toString()));
this.emit('end');
}
function bundleShare(b, config) {
b.bundle()
.on('error', logError)
.pipe(source(config.destFilename))
.pipe(gulp.dest(config.destDir));
}
function browserifyShare(config, watch) {
var browserifyConfig = {
cache: {},
packageCache: {},
fullPaths: true,
insertGlobals: true
};
if(process.env.NODE_ENV !== 'production'){
browserifyConfig.debug = true;
}
var b = browserify(browserifyConfig);
b.transform('browserify-css', {});
b.transform(babelify, {presets: ["es2015"]});
// Need to fix dollar sign getting effed in angular when it gets minified before we can enable
if(process.env.NODE_ENV === 'production'){
b.transform('uglifyify', {global: true});
}
if(watch) {
// if watch is enable, wrap this bundle inside watchify
b = watchify(b);
b.on('update', function(ids) {
ids.forEach(function(id){
console.log(chalk.green(id + ' finished compiling'));
});
bundleShare(b, config);
});
b.on('log', function(message){
console.log(chalk.magenta(message));
});
}
// source to watch
b.add(config.sourceFile);
bundleShare(b, config);
}
gulp.task('minify-css', function() {
var minifyConfig = {compatibility: 'ie8'};
if(process.env.NODE_ENV !== 'production'){
minifyConfig.debug = true;
}
return gulp.src('./web-app/css/*/*.css')
.pipe(cleanCSS(minifyConfig))
.pipe(gulp.dest('./web-app/css'))
;
});
gulp.task('browserify', ['minify-css'], function(){
glob(browserifyables, {}, function(err, files){
_.each(files, function(file){
browserifyShare({
sourceFile: file,
destDir: path.dirname(file),
destFilename: path.basename(file).replace('-browserify', '')
});
});
});
});
I run the gulp task using
NODE_ENV='production' gulp browserify
The gulp tasks complete but does not terminate. The following is the output
[22:40:57] Using gulpfile ~/some/dir/Gulpfile.js
[22:40:57] Starting 'minify-css'...
[22:40:58] Finished 'minify-css' after 565 ms
[22:40:58] Starting 'browserify'...
[22:40:58] Finished 'browserify' after 2.12 ms
This slows down my build on jenkins considerably.
However if i comment out this line:
b.add(config.sourceFile);
The tasks exit but then it does not work ( for obvious reasons ).
So not sure what I am missing here. I need to figure out what prevents the task from exiting.

Gulp copies file but it is empty

I'm having a strange problem. I'm using gulp to compile a react app and am having it copy index.html to the appropriate web directory. When I first run gulp, all runs as expected, but when the file changes and the watch task is run, gulp copies an empty version of the file to the web directory. Does anyone know why this might be happening? Here is my gulpfile.js:
var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var livereload = require('gulp-livereload');
gulp.task('livereload', function() {
console.log('reloading');
livereload();
});
gulp.task('copyindextodist', function() {
gulp.src('app/index.html')
.pipe(gulp.dest('dist'));
});
gulp.task('compilejs', function() {
browserify({
entries: 'app/index.js',
extensions: ['.js'],
debug: true
})
.transform('babelify', {presets: ['es2015', 'react']})
.bundle()
.pipe(source('app.js'))
.pipe(gulp.dest('dist'));
});
gulp.task('publishapp', function() {
gulp.src('dist/*.*')
.pipe(gulp.dest('../public'));
});
gulp.task('copypaste', function() {
gulp.src('app/index.html')
.pipe(gulp.dest('../public'));
});
gulp.task('watch', function() {
livereload.listen();
gulp.watch('app/index.html', ['copyindextodist']);
gulp.watch('dist/index.html', ['publishapp']);
gulp.watch('app/index.js', ['compilejs']);
gulp.watch('dist/app.js', ['publishapp']);
});
gulp.task('default', ['copyindextodist', 'compilejs', 'publishapp', 'watch']);
I had the same problem until I defined the dependencies correctly. You can define which tasks should be completed, before the current task starts:
gulp.task('compress', ['copy'], function() {
//.... your job
});
This means that the compress task will wait for the copy task to be finished. If you don't do that, you might end up with empty/truncated files and other strange results.
Just take care that your copy tasks return a stream object.
gulp.task('copy', function() {
// "return" is the important part ;-)
return gulp.src(['filepath/**/*'])
.pipe(gulp.dest('lib/newpath'))
});
If you have multiple copy commands running in your task this is tricky, but there is an extension for this:
var gulp = require('gulp');
var merge = require('merge-stream');
gulp.task('copy', function() {
var allStreams = [
gulp.src(['node_modules/bootstrap/dist/**/*'])
.pipe(gulp.dest('lib/bootstrap')),
gulp.src(['node_modules/jquery/dist/**/*'])
.pipe(gulp.dest('lib/jquery')),
];
return merge.apply(this, allStreams);
});
gulp.task('nextTask', ['copy'], function() {
// this task formerly produced empty files, but now
// has a valid dependency on the copy stream and
// thus has all files available when processed.
});