Grunt uglify. How to minify and replace original file with result? - gruntjs

We're using grunt for dev and prod. For dev we don't perform uglify but for prod we do. Unfortunately I can't change references to script from something like this "script.js" to "script.min.js".
I've tried grunt task like this for prod environment but it is not work:
// uglify
uglify: {
options: {
drop_console: true
},
componet: {
src: [componet.path + 'script.js'],
dest: componet.path + 'script.js'
},
}
What is the best workflow to change content "script.js" with uglified version?

Try with this:
uglify: {
options: {
},
main: {
files: [{
expand: true,
src: ['yourpath/**/*.js'],
dest: ''
}]
}
}

There are different possibilities to define the grunt task, here some examples:
uglify: {
options: {
drop_console: true
},
componet: {
files: [
// map one to one
{ 'path/to/minimized01.min.js': 'path/to/source01.js' },
{ 'path/to/minimized02.min.js': 'path/to/source02.js' },
// concat several sources into a minimized destination
{ 'path/to/minimized03and04.min.js': [ 'path/to/source03.js', 'path/to/source04.js' ]},
// map all files in a folder, one to one into a destination
{ expand: true,
cwd: 'path/to/a/source/folder',
src: [ '**/*.js', '!excludeThisFile.js' ],
dest: 'path/to/a/destination/folder',
ext: 'min.js' // if you want to change each extension to min.js
}
]
}
}
And then you can run it as grunt uglify:component... I always set separate tasks for development and production, for development I'd suggest using uglify, without dropping console, and use beautify option... Even better if you use source mapping, its very useful for debugging in browsers.

Related

How to use array variable properly in gruntfile.js

Trying to use a predefined array inside of a grunt file, thought using this.js_paths would work, but doesn't seem to work as I'm getting the error, "Cannot read property IndexOf of undefined" when it comes to trying to uglify the scripts. How can I link the js_paths variable to the files src property properly instead of copying the array into the files. Would like to define it separately at the top. Is this possible?
module.exports = function(grunt) {
// loadNpmTasks from package.json file for all devDependencies that start with grunt-
require("matchdep").filterDev("grunt-*", './package.json').forEach(grunt.loadNpmTasks);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
js_paths: [
'inc/header1/js/*.js',
'!inc/header1/js/*.min.js',
'inc/header2/js/*.js',
'inc/header2/js/*.js',
'!inc/header2/js/*.min.js',
'js/*.js',
'!js/*.min.js'
],
uglify: {
options: {
mangle: true
},
build: {
files: [{
expand: true,
src: this.js_paths,
rename: function(dst, src) {
return src.replace('.js', '.min.js');
}
}]
}
},
watch: {
scripts: {
files: ['inc/header1/js/*.js', 'inc/header2/js/*.js', 'js/*.js'],
tasks: ['uglify'],
options: {
spawn: false,
}
}
}
});
grunt.registerTask('default', ['uglify', 'watch']);
};
Preferrably would like to use the same array js_paths in the watch files (since it's required there), if that makes sense? Still kinda new to using gruntfile.js
Utilize the Templates syntax. It's described in the docs as following:
Templates
Templates specified using <% %> delimiters will be automatically expanded when tasks read them from the config. Templates are expanded recursively until no more remain.
Essentially, change this.js_paths to '<%= js_paths %>' in your uglify task.
For instance:
// ...
uglify: {
options: {
mangle: true
},
build: {
files: [{
expand: true,
src: '<%= js_paths %>', // <-----
rename: function(dst, src) {
return src.replace('.js', '.min.js');
}
}]
}
},
// ...
Likewise for your watch task too.
For instance:
watch: {
scripts: {
files: '<%= js_paths %>', // <-----
tasks: ['uglify'],
options: {
spawn: false,
}
}
}

Gruntfile.js Syntax error: Warning: Task "default" not found. Use --force to continue

This is my very first attempt at configuring a Gruntfile.js and i can't seem to figure out what's causing this "Warning: Task "default" not found. Use --force to continue. Aborted due to warnings." error. Can someone please help me figure out what's wrong with my code. Find source code below:
'use strict';
module.exports = function (grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Automatically load required Grunt tasks
require('jit-grunt')(grunt);
// Define the configuration for all the tasks
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: {
src: [
'Gruntfile.js',
'app/scripts/{,*/}*.js'
]
}
}
}),
copy: {
dist: {
cwd: 'app',
src: [ '**','!styles/**/*.css','!scripts/**/*.js' ],
dest: 'dist',
expand: true
},
fonts: {
files: [
{
//for bootstrap fonts
expand: true,
dot: true,
cwd: 'bower_components/bootstrap/dist',
src: ['fonts/*.*'],
dest: 'dist'
}, {
//for font-awesome
expand: true,
dot: true,
cwd: 'bower_components/font-awesome',
src: ['fonts/*.*'],
dest: 'dist'
}
]
}
},
clean: {
build: {
src: [ 'dist/']
}
});
grunt.registerTask('build', [
'clean',
'jshint',
'copy'
]);
grunt.registerTask('build', [
'jshint'
]);
grunt.registerTask('default',['build']);
};
You have not defined a task named default. A sample, really small gruntfile.js can be found below:
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.initConfig({
copy: {
main: {
files: [
{ expand: true, src: ['**'], cwd: 'lib/font-awesome/fonts/', dest: 'fonts/', filter: 'isFile' },
]
}
}
});
grunt.registerTask('default', ['copy:main']);
};
So, in this file, I'm loading the NPM package called grunt-contrib-copy. Then in the config, I specify the config for the copy sub-task by giving it a name of main and including the rules below that. Each grunt sub-task has it's own format of options and configuration that you can follow. Finally, I'm saying that the Grunt task runner should have a task named default followed by an order of operations. The first (and only) in my case is the copy sub-task and the main ruleset. In your case, this may be copy:dist for the copy operation.
Hope that helps get you started.
I've found the syntax error. These characters ')};' closed the config in the wrong place (line 30) which disrupted the flow of the program. so i just had to remove them and put them in their rightful place way down on line 67.
Sorry it turned out to be just a silly mistake on my part and probably nothing relevant to anyone else.

Grunt contrib Less - issue with partial files

I am facing an issue with grunt-contrib-less plugin.
Problem Explanation
I have multiple less partials files which i am including in a main.less file. My grunt watch listen for changes in less files and run the less task. The problem is grunt contrib less is compiling the partials individually which throws error as some variable not define (which is actually defined in _var.less file).
I tried to negate the partials in my grunt file, but its not working.
here is my grunt config.
less: {
development: {
options: {
compress: false,
yuicompress: false/*,
optimization: 2*/
},
files: [
{
expand: true,
cwd: 'css/less',
//src: ['*.less'],
src: ['*.less', "!_*.less"],
// dest: 'dest/css/',
dest: 'css/',
ext: '.css'
}
]
}
},
watch: {
styles: {
files: ['css/less/*.less'], // which files to watch
tasks: ['less'],
options: {
nospawn: true
}
}
}
Please tell me what is wrong here.

Grunt "copy" noProcess option is not working?

It's look like noProcess option is ignored in my init settings for "copy" plugin.
Any one knows why this is happening ? I dont get any errors but the source folder/files (src/source/**) that it suppose to be ignored is copied over to destiantion folder.
Those are my settings in the init function:
copy: {
options: {
noProcess: ["!src/source/**"]
},
prod: {
files: [
{
expand: true,
src: ['src/**'],
dest: 'build/'
}
]
}
}
Definition
grunt.loadNpmTasks('grunt-contrib-copy');
Call:
grunt.registerTask("prod", ["concat", "uglify", "htmlmin", "imagemin", "copy"]);
Anyone see the problem or whats more important a solution ?
It looks like this setting does the job. But still, I do not understand how the noProcess option should be used to work as expected.
copy: {
prod: {
files: [
{
expand: true,
src: ['src/**', '!src/source/**/*', '!src/source'],
dest: 'build/'
}
]
}
}

Grunt SCSS - Not reloading

I am trying to achieve a smooth workflow.
my problem:
My JS modifications are shown and minified and the live reload works fine. When I make changes to my SCSS files they do not run under the run command:
grunt
or the grunt plugin:
grunt watch
It only works when I invoke:
grunt sass
This was the output from the 'grunt sass' console window:
Macintosh:grunt-test Neil$ grunt sass
Running "sass:dist" (sass) task
File "css/global.css" created.
Done, without errors.
Notes:
When I run 'grunt watch' on a sass file I have noticed that grunt runs the minification on the javascript for no reason. Surely this be invoked when that file or one of its dependencies is effected?
Gruntfile.js Contents:
module.exports = function(grunt) {
// 1. All configuration goes here
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
options: {
files: ['css/*.css'],
livereload: true
},
css: {
files: ['css/*.scss'],
tasks: ['sass'],
options: {
spawn: false,
}
},
scripts: {
files: ['js/*.js', 'scss/*.scss'],
tasks: ['concat', 'uglify'],
options: {
spawn: false,
}
}
},
sass: {
dist: {
options: {
style: 'compressed'
},
expand: true,
cwd: 'scss/',
src: ['*.scss'],
dest: 'css/',
ext: '.css'
}
},
concat: {
// 2. Configuration for concatinating files goes here.
dist: {
src: [
'js/libs/*.js', // All JS in the libs folder
'js/global.js' // This specific file
],
dest: 'js/build/production.js',
}
},
uglify: {
build: {
src: 'js/build/production.js',
dest: 'js/build/production.min.js'
}
},
imagemin: {
dynamic: {
files: [{
expand: true,
cwd: 'images-lossy/',
src: ['**/*.{png,jpg,gif}'],
dest: 'images/'
}]
},
png: {
options: {
optimizationLevel: 7
}
},
jpg: {
options: {
progressive: true
}
}
}
});
// 3. Where we tell Grunt we plan to use this plug-in.
// CONCATENATION PLUGIN
grunt.loadNpmTasks('grunt-contrib-concat');
// MINIFY PLUGIN
grunt.loadNpmTasks('grunt-contrib-uglify');
// IMG CRUSH PLUGIN
grunt.loadNpmTasks('grunt-contrib-imagemin');
// GRUNT WATCH PLUGIN
grunt.loadNpmTasks('grunt-contrib-watch');
// SASS LIBARY PLUGIN
grunt.loadNpmTasks('grunt-contrib-sass');
// 4. Where we tell Grunt what to do when we type "grunt" into the terminal.
grunt.registerTask('default', ['sass','concat', 'uglify', 'imagemin', 'watch']);
};
I hope the above information helps. I have previously used Codekit, and it a really great app. I want to move to grunt but maybe my configuration file is incorrect I am close.
Any help would be greatly appreciated.
Neil
It looks like both of your issues occur within the watch configuration.
First, the reason the SASS task isn't working during watch is due to the files entry pointing to the wrong location. Your current files entry points to the "css" folder, but it should point to the "scss" folder, according to what you've specified in the actual "sass" task. In other words, your entry should be: files: ['scss/*.scss'].
css: {
files: ['scss/*.scss'],
tasks: ['sass'],
options: {
spawn: false,
}
}
Second, the JavaScript minification occurs during the watch whenever a SASS file changes because you have it listed here:
scripts: {
files: ['js/*.js', 'scss/*.scss'], // <-- scss is covered here
tasks: ['concat', 'uglify'],
options: {
spawn: false,
}
}
Change it to files: ['js/*.js'], instead to have the watch task kick in for JavaScript files only.
Once you address those issues, if things are slightly working you might want to expand the patterns so that it covers all files in the subdirectories for your JavaScript, CSS, SASS, etc. For example, js/*.js includes all .js files under the js folder, while js/**/*.js covers the js folder and its subfolders. You can read more under the GruntJS "globbing patterns" documentation.
EDIT: here's how the updated watch should look like...
watch: {
options: {
livereload: true
},
// css is really for Sass
css: {
files: ['scss/*.scss'],
tasks: ['sass'],
options: {
spawn: false,
}
},
// scripts will detect js changes
scripts: {
files: ['js/**/*.js'],
tasks: ['jshint', 'concat', 'uglify'],
options: {
spawn: false,
}
}
},
As mentioned, your individual tasks might need to use the ** pattern similar to what I've done with the "scripts" entry above: js/**/*.js

Resources