Enabling live reload with Grunt on a Vagrant-hosted project - gruntjs

My project uses Vagrant; it's served as https://domain.dev:8443.
The goal is to reload the CSS into the page whenever the CSS changes, without requiring a full page reload.
I am trying to achieve this without any manual action, this means I do not want to use a browser-plugin. Everything should be able to get up and running using the task grunt develop.
grunt-contrib-watch is used to watch 3 different targets, namely css, scss and js. Because these tasks are concurrent, but sadly blocking, I also use grunt-focus to run these 3 tasks at the same time, which correctly works. Whenever changing any file that should be watched, I get a notification in my console that it changed. Awesome.
grunt-contrib-watch recommends connect-livereload, which is middleware for grunt-contrib-connect. This would enable me to get the desired behaviour, but I do not know how to set it up properly.
This is my Gruntfile, note that I did leave out a lot of tasks that are not related to this issue, so it will not run.
module.exports = function(grunt) {
'use strict';
//Load all dependencies that we need
var ConnectLiveReload = require('connect-livereload')();
//Load all packages that we need into Grunt
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-focus');
//The watcher needs a clean object to store data to
var files = Object.create(null);
//Initialize Grunt with the options for all tasks
grunt.initConfig({
connect: {
options: {
port: 0
},
develop: {
options: {
middleware: function(connect) {
return [ConnectLiveReload];
}
}
}
},
focus: {
develop: {}
},
watch: {
scss: {
tasks: ['build'],
files: ['app/webroot/**/*.scss'],
options: {
spawn: false
}
},
css: {
files: ['app/webroot/**/*.css'],
options: {
spawn: false,
livereload: true
}
},
js: {
tasks: ['jasmine:test', 'eslint'],
files: dictionary.javascript,
options: {
spawn: false
}
}
}
});
//Sets the target config for specific tasks 200ms after the last change
var onChange = grunt.util._.debounce(function() {
var target = getTarget();
grunt.config('eslint.target', target);
}, 200);
//Listen to changed files using the watcher
grunt.event.on('watch', function(action, filepath, target) {
files[filepath] = action;
onChange();
});
/**
* Gets the path from the dictionary and adds a JavaScript file selector to it.
*
* #method getPath
* #param [pathkey=webroot]
* #return {String}
*/
function getPath(pathkey) {
pathkey = pathkey || 'webroot';
return (dictionary[pathkey] || pathkey) + '/*.js';
}
/**
* Gets an array of the last-changed files as detected by the watcher.
*
* #method getTarget
* #return {Array}
*/
function getTarget() {
var target = Object.keys(files);
files = Object.create(null);
return target;
}
/**
* #task develop
* #runs watch:css
* #runs watch:scss
* #runs watch:js
*/
grunt.registerTask('develop', 'Start the automated development tasks', function() {
grunt.task.run(['connect:develop', 'focus:develop']);
});
};
http://localhost:35729/livereload.js is a valid file and I can visit in my browser, but the script is not being added to the page. How would I do this?

Related

SyntaxError: Unexpected token { in Gruntfile.js

I don't manage to configure grunt. I have followed all the steps from Magento2 but I receive this syntax error.
grunt
Loading "Gruntfile.js" tasks...ERROR
>> SyntaxError: Unexpected token {
Warning: Task "default" not found. Use --force to continue.
Aborted due to warnings.
I have reinstalled both the grunt and the node.js, but it doesn't work.
Has anybody had the same problem?
Below you can see the Gruntfile.js ( that is original) posted.
Is it an error of this file or is there another problem?
Gruntfile.js
module.exports = function (grunt) {
'use strict';
var _ = require('underscore'),
path = require('path'),
filesRouter = require('./dev/tools/grunt/tools/files-router'),
configDir = './dev/tools/grunt/configs',
tasks = grunt.file.expand('./dev/tools/grunt/tasks/*'),
themes;
filesRouter.set('themes', 'dev/tools/grunt/configs/themes');
themes = filesRouter.get('themes');
tasks = _.map(tasks, function(task){ return task.replace('.js', '') });
tasks.push('time-grunt');
tasks.forEach(function (task) {
require(task)(grunt);
});
require('load-grunt-config')(grunt, {
configPath: path.join(__dirname, configDir),
init: true,
jitGrunt: {
staticMappings: {
usebanner: 'grunt-banner'
}
}
});
_.each({
/**
* Assembling tasks.
* ToDo: define default tasks.
*/
default: function () {
grunt.log.subhead('I\'m default task and at the moment I\'m empty, sorry :/');
},
/**
* Production preparation task.
*/
prod: function (component) {
var tasks = [
'less',
'autoprefixer',
'cssmin',
'usebanner'
].map(function(task){
return task + ':' + component;
});
if (typeof component === 'undefined') {
grunt.log.subhead('Tip: Please make sure that u specify prod subtask. By default prod task do nothing');
} else {
grunt.task.run(tasks);
}
},
/**
* Refresh themes.
*/
refresh: function () {
var tasks = [
'clean',
'exec:all'
];
_.each(themes, function(theme, name) {
tasks.push('less:' + name);
});
grunt.task.run(tasks);
},
/**
* Documentation
*/
documentation: [
'replace:documentation',
'less:documentation',
'styledocco:documentation',
'usebanner:documentationCss',
'usebanner:documentationLess',
'usebanner:documentationHtml',
'clean:var',
'clean:pub'
],
'legacy-build': [
'mage-minify:legacy'
],
spec: function (theme) {
var runner = require('./dev/tests/js/jasmine/spec_runner');
runner.init(grunt, { theme: theme });
grunt.task.run(runner.getTasks());
}
}, function (task, name) {
grunt.registerTask(name, task);
});
};
Thanks in advance!
I was getting the same error.
I installed node using the following commands and error resolved.
curl -sL https://deb.nodesource.com/setup_8.x | sudo bash -
sudo apt install nodejs
node -v
npm -v
Hope this helps!

CSS not loading correctly on Jekyll (GitHub)

My github page's css is being generated as
http://name.github.io/project/assets/css/main.css, but in the index.html it points to http://name.github.io/assets/css/main.css
I am using Jekyll with Gulp and SASS. I know this would work fine on a real .com domain but how do I make it correct on GitHub Pages?
My gulpfile.js
var gulp = require('gulp');
var browserSync = require('browser-sync');
var sass = require('gulp-sass');
var prefix = require('gulp-autoprefixer');
var plumber = require('gulp-plumber');
var cp = require('child_process');
var jade = require('gulp-jade');
var messages = {
jekyllBuild: '<span style="color: grey">Running:</span> $ jekyll build'
};
/**
* Build the Jekyll Site
*/
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
*/
gulp.task('jekyll-rebuild', ['jekyll-build'], function () {
browserSync.reload();
});
/**
* Wait for jekyll-build, then launch the Server
*/
gulp.task('browser-sync', ['sass', 'jekyll-build'], function() {
browserSync({
server: {
baseDir: '_site'
}
});
});
/**
* Compile files from _scss into both _site/css (for live injecting) and site (for future jekyll builds)
*/
gulp.task('sass', function () {
return gulp.src('assets/css/main.scss')
.pipe(sass({
includePaths: ['css'],
onError: browserSync.notify
}))
.pipe(plumber())
.pipe(prefix(['last 15 versions', '> 1%', 'ie 8', 'ie 7'], { cascade: true }))
.pipe(gulp.dest('_site/assets/css'))
.pipe(browserSync.reload({stream:true}))
.pipe(gulp.dest('assets/css'));
});
/*
* trying to Gulp stuff
*/
gulp.task('jade', function() {
return gulp.src('_jadefiles/*.jade')
.pipe(jade())
.pipe(gulp.dest('_includes'));
})
/**
* Watch scss files for changes & recompile
* Watch html/md files, run jekyll & reload BrowserSync
*/
gulp.task('watch', function () {
gulp.watch('assets/css/**', ['sass']);
gulp.watch('assets/js/**', ['jekyll-rebuild']);
gulp.watch(['index.html', '_layouts/*.html', '_includes/*'], ['jekyll-rebuild']);
gulp.watch(['assets/js/**'], ['jekyll-rebuild']);
gulp.watch('_jadefiles/*.jade', ['jade']);
});
/**
* Default task, running just `gulp` will compile the sass,
* compile the jekyll site, launch BrowserSync & watch files.
*/
gulp.task('default', ['browser-sync', 'watch']);
The _site folder is where all the generated HTML and CSS is. The only solution I can think of is moving the contents from the _site folder to the root of my git repo and deleting everything else that was there before.
In my _config.yml, the basedir is even set to baseurl: github-project-name but still doesn't load.
In _config.yml, set :
baseurl: /project
Then call your assets with :
<link rel="stylesheet" href="{{ "/assets/css/main.css, " | prepend: site.baseurl }}">

How to avoid unnecessary uglifying in GruntJS?

I have a grunt file with the following definition:
uglify: {
build: {
src: 'www/temp/application.js', // a concatenation of files via grunt-contrib-concat
dest: 'www/temp/application.min.js'
}
},
what I would really like to do is to recompute the final application.min.js only in case that application.js file was changed. More precisely, I want to add the condition:
# pseudocode
if (getFileContents(application.js) == getFileContents(previously.uglified.application.js)) {
// do nothing
} else {
// run uglifying on application.js
}
Reason:
I deploy my project by git and uglifying is relatively slow (3+ seconds) and moreover, it is unnecessary since I don't change JS files often.
There are several possible solutions:
You can create your own grunt task that will check files for last modify time using for example fs.stat then run uglify task through grunt.task.run with prepared options as argument.
Or you can build files object dynamically passing it through filter function:
var fs = require('fs');
module.exports = function (grunt) {
function filterChanged(files) {
var mtime = '',
stats;
for (var dest in files) {
stats = fs.statSync(files[dest]);
try {
mtime = fs.readFileSync(files[dest] + '.mtime', 'utf8');
}
catch (ex) {
fs.writeFileSync(files[dest] + '.mtime', stats.mtime, 'utf8');
return files;
}
if (stats.mtime == mtime || !mtime) {
delete files[dest];
}
else {
fs.writeFileSync(files[dest] + '.mtime', stats.mtime, 'utf8');
}
}
return files;
}
grunt.initConfig({
uglify: {
build: {
files: filterChanged({
'www/temp/application.min.js': 'www/temp/application.js'
})
}
}
});
};
This causes invoke of filterChanged function every time uglify task runs.

registerMultiTask.js in grunt-horde

I'm trying to configure grunt-horde so that I can have multiple builds all using a centrally managed task configuration.
The documentation provides the following example of a registerMultiTasks.js file, but I can't get it to work
module.exports = function(grunt) {
var myMultiTask = require('./multi-tasks/secret-sauce.js');
return {
myMultiTask: ['some description', myMultiTask]
};
};
Even if I replace their example with something more simple:
module.exports = function(grunt) {
return {
demo: ['Demo', function() {
console.info('hello');
}]
};
};
When I run grunt demo:test the output is:
Running "demo:test" (demo) task
Verifying property demo.test exists in config...ERROR
>> Unable to process task.
Warning: Required config property "demo.test" missing. Use --force to continue.
Aborted due to warnings.
When I run grunt --help the demo task shows up in the list. Thinking about the warning message I've also tried the following, but again with no luck.
module.exports = function(grunt) {
return {
demo: ['Demo', function(){
return {test: function(){console.info('hello');}};
}]
};
};
...what am I doing wrong?
I figured it out - you need to define the configuration for each target of the multitasks:
initConfig/demo.js
module.exports = function() {
'use strict';
return {
test: {
foo: 'bar'
}
};
};
You can then access this configuration data and the target from within the multitask function:
registerMultiTask.js
module.exports = function(grunt) {
return {
demo: ['Demo', function() {
grunt.log.writeln('target: ' + this.target);
grunt.log.writeln('foo: ' + this.data.foo);
}]
};
};

Conditionally running tasks in grunt if some files are changed

I'm new to Grunt, and from what I understood up till now, Grunt has the "watch" task, which continuously checks files for modifications, and each time modification happens, runs corresponding tasks.
What I'm looking for would be a kind of discrete version of this - a task, that would run other tasks, if and only if some files were changed since the last build.
Seems to be a natural thing to ask for, but I couldn't find this. Is it just me, or is this really an issue?
Configuration file should look like this:
grunt.initConfig({
foo: {
files: "foo/*"
// some task
},
bar: {
files: "bar/*"
// some other task
},
ifModified: {
foo: {
files: "foo/*",
tasks: ['foo']
},
bar: {
files: 'bar/*',
tasks: ['bar', 'foo']
}
}
});
grunt.registerTask('default', ['bar', 'foo']);
Running grunt should always execute tasks 'bar', 'foo', while running grunt ifModified should execute any tasks only if some of the files were actually changed since the previous build.
Made my own task for that. It turned out to be not hard, here is the code:
build/tasks/if-modified.js:
var fs = require('fs');
var crypto = require('crypto');
module.exports = function (grunt) {
grunt.registerMultiTask('if-modified', 'Conditionally running tasks if files are changed.', function () {
var options = this.options({});
grunt.verbose.writeflags(options, 'Options');
var hashes = {};
if (grunt.file.exists(options.hashFile)) {
try {
hashes = grunt.file.readJSON(options.hashFile);
}
catch (err) {
grunt.log.warn(err);
}
}
grunt.verbose.writeflags(hashes, 'Hashes');
var md5 = crypto.createHash('md5');
this.files.forEach(function (f) {
f.src.forEach(function (filepath) {
var stats = fs.statSync(filepath);
md5.update(JSON.stringify({
filepath: filepath,
isFile: stats.isFile(),
size: stats.size,
ctime: stats.ctime,
mtime: stats.mtime
}));
});
});
var hash = md5.digest('hex');
grunt.verbose.writeln('Hash: ' + hash);
if (hash != hashes[this.target]) {
grunt.log.writeln('Something changed, executing tasks: ' + JSON.stringify(options.tasks));
grunt.task.run(options.tasks);
hashes[this.target] = hash;
grunt.file.write(options.hashFile, JSON.stringify(hashes));
}
else
grunt.log.writeln('Nothing changed.');
});
};
Gruntfile.js:
grunt.initConfig({
foo: {
src: ["foo/**/*"],
dest: "foo-dest"
// some task
},
bar: {
src: ["bar/**/*", "foo-dest"]
// some other task
},
'if-modified': {
options: {
hashFile: 'build/hashes.json'
},
foo: {
src: ['foo/**/*', 'Gruntfile.js', 'package.json'],
options: {tasks: ['foo']}
},
bar: {
src: ['bar/**/*', "foo-dest", 'Gruntfile.js', 'package.json'],
options: {tasks: ['bar']}
}
}
});
grunt.loadTasks('build/tasks'); // if-modified.js in this dir
grunt.registerTask('default', ['foo', 'bar']);
run:
grunt if-modified
You could create a task that runs conditionally other tasks, from https://github.com/gruntjs/grunt/wiki/Creating-tasks :
grunt.registerTask('foo', 'My "foo" task.', function() {
// Enqueue "bar" and "baz" tasks, to run after "foo" finishes, in-order.
grunt.task.run('bar', 'baz');
// Or:
grunt.task.run(['bar', 'baz']);
});
What you need might be grunt-newer :
The newer task will configure another task to run with src files that are a) newer than the dest files or b) newer than the last successful run (if there are no dest files). See below for examples and more detail.
https://github.com/tschaub/grunt-newer

Resources