I am a gruntjs newbie and am trying to write a build for JS frontend. A requirement is set so that all the source files that enter the build process (concatenation, minification) must be defined in an external file:
|-config
|- js.json
|-src
|- js
|- a.js
|- b.js
|- Gruntfile.js
|- package.json
I have simplified the project structure to illustrate the problem. The config/js.json looks like this:
[
"<%=js_dir%>/a.js",
"<%=js_dir%>/b.js"
]
Gruntfile.js looks like this:
module.exports = function(grunt) {
grunt.initConfig({
concat: {
"options": {"separator": ";"},
"build": {
"src": "<%= grunt.template.process(grunt.file.read('./config/js.json'),{data: {js_dir: './src/js'}})%>"
,
"dest": "build/app.js"
}
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.registerTask('default', ['concat']);
};
When I run it an empty output file is made, because the source list is empty:
...
Reading ./config/js.json...OK
Files: [no src] -> build/app.js
Reading ./config/js.json...OK
Writing out...OK
Writing build/app.js...OK
File "build/app.js" created.
Done, without errors.
To verify my logic I dumped the processed sources list by changing the src property like this:
"src": "<%= grunt.file.write('out',grunt.template.process(grunt.file.read('./config/js.json'),{data: {js_dir: './src/js'}}))%>"
The contents of the out file show that template processing logic is valid:
[
".src/js/a.js",
".src/js/b.js"
]
Since the src property accepts a hardcoded JSON array of source files my guess is that the binding of the sources list is done before the templating is done.
The gruntjs verbose output shows the reading of config/js.json before and after the concatenation which confuses me.
I tried rewriting the config/js.json file so that all the JSON array fits in one line but to no avail.
If this can be done, please tell me how. If it can't be done please tell me why.
My environment:
grunt: grunt-cli v0.1.9, grunt v0.4.1
nodejs: v0.11.6-pre
os: Linux localhost 3.2.0-23-generic #36-Ubuntu x86_64 GNU/Linux
The Grunt config will process templates as the config is read. So you dont need an additional grunt.template.process. Assuming config/js.json is valid JSON just do this:
module.exports = function(grunt) {
grunt.initConfig({
js_dir: 'src/js',
concat: {
options: {separator: ";"},
build: {
src: require('./config/js.json'),
dest: "build/app.js"
}
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.registerTask('default', ['concat']);
};
Always remember Gruntfiles are JavaScript and not JSON.
Related
I have an app folder where I want to replace http://localhost:8000 for http://fomoapp-melbourne.rhcloud.com in two files: companies-list.component.ts and events-list.component.ts. I am trying to use grunt-replace-string plugin and it seemingly runs successfully with green Done result and no errors, but no replacement happens.
Here is how Gruntfile.js looks like:
module.exports = function(grunt){
[
'grunt-string-replace',
].forEach(function(task){
grunt.loadNpmTasks(task);
});
// configure plugins
grunt.initConfig({
'string-replace': {
dist: {
files: {
'./app/': ['companies-list.component.ts','events-list.component.ts'],
},
options: {
replacements: [{
pattern: 'http://localhost:8000',
replacement: 'http://fomoapp-melbourne.rhcloud.com',
}]
}
}
},
});
// register tasks
grunt.registerTask('default', ['string-replace']);
};
The Grunt Files object is for specifying a mapping of source files to destination files. The purpose of this mapping is to tell Grunt to get the contents of the files in source, do something to the contents, and then write the response to a new file in the destination folder.
It looks to me from your configuration that you want Grunt to rewrite two files in the app/ directory. This is not going to work. I will bet that if you run grunt with the verbose option, grunt --verbose, your output will contain the following:
Files: [no src] -> ./app/
This is because Grunt cannot find the source files because you need to specify their relative paths.
It's up to you how you want to structure your app, but you might want to have a src/ folder and a dist/ folder under app/. If you choose to build your files objects dynamically, your config might look something like this:
files: [{
expand: true,
cwd: './app/src/',
dest: './app/dest/',
src: ['companies-list.component.ts', 'events-list.component.ts']
}]
Additionally, the documentation for grunt-string-replace states:
If the pattern is a string, only the first occurrence will be replaced, as stated on String.prototype.replace.
This means that if you want multiple instances of your string to be replaced, you must provide a Regular Expression literal. For example:
replacements: [{
pattern: /http:\/\/localhost:8000/g,
replacement: 'http://fomoapp-melbourne.rhcloud.com'
}]
I'm trying to use the grunt-modernizr plugin in my project but I'm receiving the following output when I run tasks:
Running "modernizr:dist" (modernizr) task
>> Explicitly including these tests:
>> pointerevents
Looking for Modernizr references
I'm not receiving any type of error the terminal just goes back to the directory that I'm in, as if it's just giving up.
Here is my grunt file:
module.exports = function(grunt) {
grunt.initConfig ({
// Do grunt-related things in here
pkg: grunt.file.readJSON('package.json'),
modernizr: {
dist: {
"dest": "javascripts/modernizr-custom.js",
"parseFiles": true,
"customTests": [],
"devFile": "javascripts/modernizr-custom.js",
"outputFile": "javascripts/min/modernizr-custom.min.js",
"tests": [
"pointerevents",
"css/pointerevents"
],
"extensibility": [
"setClasses"
],
"uglify": false
}
},
cssmin: {
target: {
files: {
'css/min/bootstrap.min.css': ['css/bootstrap.css']
}
}
},
});
grunt.loadNpmTasks("grunt-modernizr");
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.registerTask('default',['modernizr', 'cssmin']);
};
Output from running grunt --verbose:
Initializing
Command-line options: --verbose
Reading "gruntfile.js" Gruntfile...OK
Registering Gruntfile tasks.
Reading package.json...OK
Parsing package.json...OK
Initializing config...OK
Registering "grunt-modernizr" local Npm module tasks.
Reading /Applications/MAMP/htdocs/bootstrap-three-wordpress/wp-content/themes/brandozz/node_modules/grunt-modernizr/package.json...OK
Parsing /Applications/MAMP/htdocs/bootstrap-three-wordpress/wp-content/themes/brandozz/node_modules/grunt-modernizr/package.json...OK
Loading "modernizr.js" tasks...OK
+ modernizr
Registering "grunt-contrib-cssmin" local Npm module tasks.
Reading /Applications/MAMP/htdocs/bootstrap-three-wordpress/wp-content/themes/brandozz/node_modules/grunt-contrib-cssmin/package.json...OK
Parsing /Applications/MAMP/htdocs/bootstrap-three-wordpress/wp-content/themes/brandozz/node_modules/grunt-contrib-cssmin/package.json...OK
Loading "cssmin.js" tasks...OK
+ cssmin
Loading "gruntfile.js" tasks...OK
+ default
No tasks specified, running default tasks.
Running tasks: default
Running "default" task
Running "modernizr" task
Running "modernizr:dist" (modernizr) task
Verifying property modernizr.dist exists in config...OK
Files: -> javascripts/modernizr-custom.js
Verifying property modernizr exists in config...OK
>> Explicitly including these tests:
>> pointerevents
Looking for Modernizr references
This is something I just came across too and seems to be grunt-modernizr stopping after customizr doesn't find any files to crawl (it crawls by default).
If you add "crawl": false to your modernizr:dist task that should fix the problem.
Also, I think "extensibility": [ "setClasses" ], should be "options": [ "setClasses" ],.
To use the grunt-modernizr task to crawl your code for Modernizr references you'll have to look at the config properties for the customizr task as this is part of grunt-modernizr 's node_modules:
modernizr: {
dist: {
dest: 'bower_components/modernizr/build/modernizr.custom.js',
uglify: false,
options: [
'setClasses',
'addTest'
],
files: {
src: ['js/app/**/*.js', 'js/app/*.js']
}
}
}
devFile: doesn't seem to matter where you point at
dest: instead of outputFile, note I'm just outputting to a build directory that's not part of the package
uglify: false if you have other minifying options like bundleconfig.json
options: to bypass the default options { "setClasses", "addTest", "html5printshiv", "testProp", "fnBind" }
files: to enlist your crawlable director(y|ies), make sure you take care of the root files and/or subdirectories as well
Load the required tasks, in my case:
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-modernizr');
grunt.loadNpmTasks('grunt-contrib-copy');
Refer to the 'modernizr:dist' task => grunt.registerTask('default', ['clean', 'modernizr:dist', 'copy']);
Which results in an unminified 34kb file:
Running "clean:files" (clean) task
19 paths cleaned.
Running "modernizr:dist" (modernizr) task
Looking for Modernizr references
1 match in js/app/classes/yambo.options.js
bgpositionxy
1 match in js/app/modules/yambo.audio.js
audio
Ready to build using these settings:
setClasses, addTest
Building your customized Modernizr...OK
Success! Saved file to bower_components/modernizr/build/modernizr.custom.js
Process terminated with code 0.
Running "copy:main" (copy) task
Copied 11 files
Done, without errors.
This way there's no need to even go to the online build to add a feature test. Simply reference Modernizr throughout your js code:
window.Yambo = (function($, modernizr, ns){
ns.Audio = {
extension: (function () {
return modernizr && modernizr.audio.mp3
? 'mp3'
: modernizr.audio.ogg
? 'ogg'
: 'wav';
}())
};
return ns;
}(window.jQuery, window.Modernizr, window.Yambo || {}));
Make sure to use the correct property name for a feature detection, so customizr can pick it up and provide a test to your custom build.
This should be also possible for css but haven't been testing that for the moment.
It looks like you missed source files.
http://gruntjs.com/configuring-tasks#files-object-format
Try to include
"dist": {
"files": {
"src": ['!<%= appDir %>assets/js/bower/modernizr/**']
}
}
I am stuck writing a Gruntfile which aim is to convert a bunch of Markdown files to PDF dynamically. Giving the current folder hierarchy:
root/
|_subfolder1
| |_filename1.md
|_subfolder2
|_filename2.md
...
|_node_modules
|_subfolderN
|filenameN.md
I would like to run a Markdown to PDF task which would process the md file and ouput a PDF file with the matching filename in the same output directory.
I did create a custom task which is parsing current directory, ignoring the mode_modules folder and get the markdown file, but I don't know how to configure the md2pdf task with the good properties to reflect dynamic folder mapping.
Here's my current Gruntfile:
module.exports = function(grunt) {
// 1 - Configuration
grunt.initConfig({
md2pdf: {
}
});
// 2 - Plugins
grunt.loadNpmTasks('grunt-md2pdf');
// 3 - Task registering
grunt.registerTask('default', 'Get Subfolders', function() {
grunt.file.recurse('.', callback);
function callback(abspath, rootdir, subdir, filename) {
var filenameOutExt;
// if current occurence is a file subdir == undefined
// checking subdir to true means it's not undefined and
// the current path is a directory
if(subdir) {
// excluding node_modules folder
if (!subdir.match('node_modules')) {
// only process markdown files
if(filename.match('.md')) {
filenameOutExt = filename.split('.')[0];
// now for each markdown files, run md2pdf task
// and ouput filenameOutExt.pdf in same folder
// as the input files
}
}
}
}
});
};
I am using this plugin: https://www.npmjs.com/package/grunt-md2pdf
So my questions is how should I configure the md2pdf task to pass it the markdown files and generate matching filename pdf output in same directory.
Output should be:
root/
|_subfolder1
| |_filename1.md
|_filename1.pdf
|_subfolder2
|_filename2.md
|_filename2.pdf
...
|_node_modules
|_subfolderN
|filenameN.md
|_filenameN.pdf
Thanks a lot
According to this line, this task uses the grunt.files utilitary function. This makes things easier for us!
First, it's not usual in grunt to create a different task to find the files you need in any other task.
That is, each task should receive the files it needs to operate on. For example...
coffee:
main:
files: [
expand: true
cwd: 'assets/script'
src: ['**/*.coffee']
dest: "assets/script"
ext: '.js'
]
(Note that this config is in a Gruntfile.coffee file, hence the CoffeeScript syntax)
This type of file configuration using glob expansion is one of the most common. You can find details in the documentation.
It's pretty obvious:
In every directory (**), take everything (/*) from assets/script/ that ends with .coffee. Put it into assets/script. Rename extensions to .js.
So, your task can probably be configured like that:
md2pdf: {
main: {
files: [ {
expand: true,
src: ['**/*.md', '!node_modules/**/*'],
dest: "pdf/"
} ]
}
}
Ok figured it out !
module.exports = function(grunt) {
// 2 - Plugins
grunt.loadNpmTasks('grunt-md2pdf');
grunt.registerTask('default', 'Dynamically generate PDF from MD', function() {
grunt.file.expand("./**/*.md").forEach( function(file) {
if(!file.match('./node_modules')) {
var md2pdf = grunt.config.get('md2pdf') || {};
md2pdf[file] = {
src: file,
dest: file + '.pdf'
};
grunt.config.set('md2pdf', md2pdf);
}
});
grunt.task.run('md2pdf');
});
};
I have an Angular project with potentially many modules. Each module has it's own directory with subdirectories for controllers, directives, services, etc. Something like this:
src
|-- js
|-- modules
|-- moduleOne
| module.js
|-- controllers
| listController.js
| detailController.js
|-- directives
| listItem.js
| summaryWidget.js
|-- filters
|-- services
| moduleService.js
My build essentially bundles and compiles files from src/ and puts into dev/, then minifies the files in dev/ and moves into prod/. During dev, the server points to the dev/ folder and in production, the server points to the prod/ folder (also why the files are ending in .min.js even though they are only compiled/concated). This process is working well.
Currently, my concat task is grabbing all the files in moduleOne/ and creating a single moduleOne.js file in my dev directory. This is what I want to happen, but more dynamically:
concat: {
modules: {
files: {
"dev/js/modules/moduleOne.min.js": [
"src/js/modules/moduleOne/*.js",
"src/js/modules/moduleOne/**/*.js"
],
"dev/js/modules/moduleTwo.min.js": [
"src/js/modules/moduleTwo/*.js",
"src/js/modules/moduleTwo/**/*.js"
]
}
}
}
The problem is that I have to do this for every module, but don't think I would need to.
I tried doing the following because it's sort of what I want to do:
concat: {
modules: {
files: [{
expand: true,
cwd: "src/js/modules",
src: "**/*.js",
dest: "dev/js/modules",
ext: ".min.js"
}]
}
}
But the result was all my files and directory structure moved over from src/ to dev/. I basically used concat to do a copy, not helpful.
I'd like to do something like this:
concat: {
modules: {
files: [{
expand: true,
cwd: "src/js/modules",
src: "**/*.js",
dest: "dev/js/modules/<foldername>.min.js", <- how do I achieve this?
}]
}
}
I've been reading a lot, but it seems that I only get close to finding the answer and am having trouble putting the concepts together. A lot of what I find is just single files into a new directory, with a rename. I'd like multiple files to single file into new directory with a rename. Cuz that's how I roll :)
So, I found the answer I was looking for.
This SO post was basically the same question with a good answer. Unfortunately it didn't come up when I was creating my question or else you wouldn't be reading this.
There was a slight tweak to my needs. I needed to do it dynamically per module instead of just one compile.js file so my final code is as follows, placed just after my initConfig():
grunt.registerTask("prepareModules", "Finds and prepares modules for concatenation.", function() {
// get all module directories
grunt.file.expand("src/js/modules/*").forEach(function (dir) {
// get the module name from the directory name
var dirName = dir.substr(dir.lastIndexOf('/')+1);
// get the current concat object from initConfig
var concat = grunt.config.get('concat') || {};
// create a subtask for each module, find all src files
// and combine into a single js file per module
concat[dirName] = {
src: [dir + '/**/*.js'],
dest: 'dev/js/modules/' + dirName + '.min.js'
};
// add module subtasks to the concat task in initConfig
grunt.config.set('concat', concat);
});
});
// the default task
grunt.registerTask("default", ["sass", "ngtemplates", "prepareModules", "concat", "uglify", "cssmin"]);
This essentially makes my concat task look like it did when I was hand coding it, but just a little simpler (and scalable!).
concat: {
...
moduleOne: {
src: "src/js/modules/moduleOne/**/*.js",
dest: "dev/js/modules/moduleOne.min.js"
},
moduleTwo:{
src: "src/js/modules/moduleTwo/**/*.js",
dest: "dev/js/modules/moduleTwo.min.js"
}
}
Another deviation I made from the SO post was that I chose not to have prepareModules run concat on it's own when it was done. My default task (which watch is setup to run during dev) still does all my processing.
This leaves me with the following structure, ready for minification into prod/:
| dev
| js
| modules
|-- moduleOne.min.js
|-- moduleTwo.min.js
I've read the grunt, sass, and compass documentation but can't find much about this error. I also saw another person with a similar error but it was due to syntax problems in their contrib.rb file, which I don't believe I have in my contrib.rb file.
Problem: I run the grunt watch task and get an error anytime I make a change to my sass (*.scss) files.
The error reads as follows:
NoMethodError on line 264 of /Library/Ruby/Gems/1.8/gems/compass-0.12.2/lib/compass/configuration/inheritance.rb: _
Run with --trace to see the full backtrace
As a result, none of my sass files are processing to my css folder. I'm new to grunt and am admittedly a little overwhelmed with the amount of initial setup I've done. I'd love any advice as to how my files might be configured incorrectly or whether there might be an error with one of the versions of compass or sass as it relates to grunt (all are most recent non-beta versions).
Here is the text of my contrib.rb file:
require "susy"
css_dir = _/css
sass_dir = _/components/sass
javascripts_dir = _/js
output_style = :compressed
My gruntfile.js :
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.initConfig({
uglify: {
my_target: {
files: {
'_/js/script.js': ['_/components/js/*.js'] //tells grunt to track and compress any .js file found in components/js folder
} //files
} // my_target
}, // uglify
compass: {
dev: {
options: {
config: 'config.rb',
force: true // <-- ???
} //options
} //dev
}, //compass
watch: {
options: { livereload: true },
scripts: {
files: ['_/components/js/*.js'],
tasks: ['uglify']
}, //scripts
sass: {
files: ['_/components/sass/*.scss'],
tasks: ['compass:dev']
}, //sass
html: {
files: ['*.html']
}
} // watch
})// initConfig
grunt.registerTask('default', 'watch'); //makes 'grunt' command automaticaly execute the watch command to monitor JS files
} //exports
And my project folder structure:
sass_first_proj
|
_(folder)
|
components
|
css
|
js
images
node_modules
|
grunt
|
grunt-contrib-compass
|
grunt-contrib-uglify
|
grunt-contrib-watch
|
matchdep
.gitignore
|
config.rb
|
gruntfile.js
|
index.html
|
package.json
Not sure if you were able to solve this, but I was receiving the same error.
I had to include a forward slash before the directories to get Grunt to the right paths. I'm using similar steps in using Grunt and Compass for my project, and I'm on my PC so I just put the paths in single quotes. Based on how your project directory is structured, the two respective lines in the config.rb file would look like this:
css_dir = '/_/css'
sass_dir = '/_/components/sass'
Also in your question, I noticed you stated it was the "contrib.rb" file, but in your file directory that it is named config.rb. You reference it in your gruntfile.js file as config.rb, as well, but I just wanted to make sure that this file in the root of your project was being named "config.rb".
I know it was a lot of setup, so I hope this works for you.
So here's the thing, I've never used a contrib.rb file when using compass with Grunt. I know you can, and if you get it working, great. but the other option is to just specify the paths in the grunt config. Of course, this all assumes that you are able to actually compile the sass files. When googling for that error, it seems that much of the time it was an issue with the contrib.rb file that caused the issue.
So with that said, maybe you could leave off the contrib.rb file and just use Grunt?
compass: {
dev: {
options: {
sassDir: "_/components/sass",
specify: "_/components/sass/**/*.scss", // might not be necessary for you
cssDir: "_/css",
javascriptsPath: "_/js",
outputStyle: "compressed",
require: "susy"
}
}
}