Testing JavaScript using grunt - gruntjs

I have to run tests against a JavaScript file using grunt framework.
Just needed any simple example to do this, the target file (/test/filename.js) has dependencies on one more file.

Basically you have to make use of grunt-execute command.
Here is the explaination:https://www.npmjs.org/package/grunt-execute
In simple words , this is what you should do for your specific requirement:
module.exports = function(grunt) {
grunt.initConfig({
execute: {
simple_target: {
// execute javascript files in a node child_process
src: ['filename.js']
}
}
})
grunt.loadNpmTasks('grunt-execute');
grunt.registerTask('default', ['execute']);
}
And also,
"grunt": "~0.4.4",
"grunt-execute": "~0.1.5"
should be present in package.json, then just do npm install

Related

Is there a way to remove important comments?

I minified my css file, but it did not get rid of
/*! important comments */.
is there a way to get rid of important comments?
I found this -
grunt-contrib-cssmin - how to remove comments from minified css
but #Rigotti answer does not work for important comments.
Thanks for your help!
Many grunt plugins will not remove the important comments as the notation /*! */ is typically used to prevent removal. However, grunt-strip-css-comment, provides the option to remove them.
You could apply the following stripCssComments Task to your minified .css file.
Gruntfile.js
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
cssmin: {
// ...
},
stripCssComments: {
options: {
preserve: false // <-- Option removes important comments.
},
dist: {
files: {
// Redefine paths as necessary.
// These should probably both be the same given your scenario.
'path/to/dest/file.min.css': 'path/to/src/file.min.css'
}
}
}
});
// Define the alias to the `stripCssComments` Task after your `cssmin` Task.
grunt.registerTask('default', ['cssmin', 'stripCssComments']);
};
Install:
cd to your project directory and run:
npm i -D grunt-strip-css-comments load-grunt-tasks
Note: grunt-strip-css-comments is loaded using the plugin load-grunt-tasks instead of the typical grunt.loadNpmTasks(...) notation, so you'll need to install that too.

With Grunt, how can I compile all *.less files, if I have global mixins and constants?

I want to organize my HTML, JS, and LESS by module. I'm already using Grunt to compile *.js and *.html from my source folders.
So I configured grunt as follows:
grunt.initConfig({
less: {
ALL: {
files: { 'compiled.css': '**/*.less' }
}
}
}
But this runs into a major problem: constants and mixins from my /helper/*.less files are not accessible to other .less files.
It seems like grunt-contrib-less compiles each individual .less file, and then combines the output, but doesn't compile anything "globally".
The only solution I can think of is to create and maintain a master.less that #imports each individual .less file. But I'm trying to achieve an extremely modular build process, and I don't have to list any HTML or JS files, so I'm really hoping to find a *.less solution too!
Thanks to #seven-phases-max for the following answer!
less-plugin-glob
Allows you to use wildcards in #import statements! Works perfectly!
// master.less
#import "helpers/**/*.less";
#import "modules/**/*.less";
And all you need to add to your Grunt configuration is the plugins option:
// Gruntfile.js
grunt.initConfig({
less: {
'MASTER': {
src: 'master.less',
dest: 'master.css',
options: {
plugins: [ require('less-plugin-glob') ]
}
}
}
});
And, don't forget, npm install less-plugin-glob.
Here's one way to achieve an effortless development experience.
However, it requires a generated file and a custom task.
Auto-generate the master.less file
Create a task that generates master.less by writing an #import statement for each *.less file:
grunt.registerTask('generate-master-less', '', function() {
generateFileList({
srcCwd: 'modules',
src: '**/*.less',
dest: 'less/master.less',
header: '// THIS FILE IS AUTOMATICALLY GENERATED BY grunt generate-master-less\n',
footer: '// THIS FILE IS AUTOMATICALLY GENERATED BY grunt generate-master-less\n',
template: '#import "<%= filename %>";\n',
join: ''
});
});
function generateFileList(options) {
var _ = grunt.util._;
var files = grunt.file.expand({ cwd: options.srcCwd }, options.src);
var results = files.map(function (filename) {
return _.template(options.template, { 'filename': filename });
});
var result = options.header + results.join(options.join) + options.footer;
grunt.file.write(options.dest, result);
}
Then, use grunt-contrib-less to just build master.less.

Grunt Livereload on a localhost started with WAMP/XAMPP/UniServerZ

I am trying to take my front-end workflow a step higher with Grunt tasks.
I have set up a couple of tasks in my Gruntfile.js. For now there are only grunt-contrib-sass and grunt-contrib-watch so that .css files are automatically recompiled whenever I make a change to my .sass files.
What I want to achieve is the following:
I want to add a task that would listen to my local server that was started with UniServerZ/XAMPP/WAMP or any other provider. I want to trigger a reload each time I edit any file in the server base directory.
I know that it is quite easy to set up such a task with, e.g. 'grunt-express' which starts a local server for you, but I really want to listen to a server started with UniServerZ/XAMPP/WAMP.
I will be grateful to see example configuration for such scenario if it is possible to achieve it.
Here is how I did it with Wamp 2.2 on Windows 7.
First, you need grunt-contrib-watch properly setup with livereload. I also use grunt-sass and not grunt-contrib-sass, because grunt-sass use Libsass. LibSass is a C/C++ port of the Sass engine, and it is faster.
To install them, use these commands :
npm install grunt-contrib-watch --save-dev
npm install grunt-sass --save-dev
Here is an example of Gruntfile :
module.exports = function(grunt) {
grunt.initConfig({
watch: {
sass: {
files: 'folder/to/your/sass/**/*.sass',
tasks: ['sass:dist'],
options: {
livereload: true,
},
},
//Watch your theme files
livereload: {
files: ['pathToTheme/*.php', 'pathToTheme/img/**/*.{png,jpg,jpeg,gif,webp,svg}'],
options: {
livereload: true
},
}
},
sass: {
options: {
includePaths: ['where/to/find/additional/#import/scss/files'],
outputStyle: 'nested',
imagePath: 'how/to/rewrite/image/path',
sourceMap: true
},
dist: {
files: {
'output/file.css': 'input/file.scss'
}
}
},
});
// Default task
grunt.registerTask('default', ['watch']);
// Load NpmTask
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-sass');
};
You could save yourself some time with load-grunt-tasks, and remove the manual loading of task :
require('load-grunt-tasks')(grunt); // npm install --save-dev load-grunt-tasks
Then I use the livereload plugin for firefox (or chrome or safari).
Start the grunt watch task, open your site on localhost, and click on the icon in your browser. Now if you edit a watched file, the page should update accordingly.
A solution exist to add the livereload js in your Wordpress automatically (in function.php):
if (in_array($_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1'))) {
wp_register_script('livereload', 'http://localhost:35729/livereload.js?snipver=1', null, false, true);
wp_enqueue_script('livereload');
}

Creating a grunt file for an angular app

My directory structure looks like below:
--myapp/
--client/
--build/
--css/
--js/
--angular/ #angular libraries here
--angular.js
--angular-resource.js
--angular-ui-router.js
--jquery/ #jquery libraries here
--jquery.js
--app.js
--index.html
--server/ #All server related files here
--Gruntfile.js
My Grunt file so far looks like this
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json');
concat: {
dist: {
src: ['client/js/angular/*.*]
dest: 'client/build/angular-build.js'
}
}
});
};
This is as far as I have gotten. Don't see any easy grunt file tutorials on this.
Th ouput I am looking for is all angular libraries in one output file. All jquery libraries in another.. all css libraries in third.
How do i achieve this ?
A few things:
You don't know it, but you're using grunt-contrib-concat, so you'd better npm install that and grunt.loadNpmTasks('grunt-contrib-concat'); it.
Concat doesn't support wildcards. This is good, because the order that these files are included is going to matter. angular.js must be included before angular-resource.js
I've included a rough template of what your Gruntfile needs to look like to accomplish this, but know that this is not the right way to do this. You should be loading your dependencies using something like bower and serving them individually, or using something like Browserify or Require.js. You'll come to see the value of that as the project progresses.
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json');
concat: {
angular: {
src: [
'client/js/angular/angular.js',
'client/js/angular/angular-resource.js',
'client/js/angular/angular-ui-router.js'
]
dest: 'client/build/angular-build.js'
},
jquery: {
src: ['client/js/jquery/jquery.js']
dest: 'client/build/jquery-build.js'
},
...
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
};

Add grunt task to linemanjs application.js

I want to add a grunt task (specifically angular-template) to my lineman application.js file. There is some documentation found here and here. However, it just tells me to add the grunt task to loadNpmTasks. The problem is that from a fresh project created using lineman, my application.js file does not have a loadNpmTasks array, nor do the comments point out where I should put it. Both examples I have found in the documentations do not show what the application.js file should look like in it's entirety.
The application.js file should look something like this (obviously the src/dest options are not configured correctly:
module.exports = function(lineman) {
return {
loadNpmTasks:['grunt-angular-templates'],
ngtemplates: {
app: {
src: '**.html',
dest: 'templates.js'
}
}
};
};
Then to run the task:
lineman grunt ngtemplates

Resources