More than 1 requirejs task in grunt for different optimization options - requirejs

I use r.js to cobble together all the js code in my SPA into 1 file. I use grunt's `grunt-contrib-requirejs' task for this, with the following:
requirejs: {
compile: {
options: {
name: 'app',
out: 'build/js/app.js',
baseUrl: 'app',
mainConfigFile: 'config/main.js',
preserveLicenseComments: true,
optimize: "none"
}
}
}
I also use a build task that zips the build folder into a zip file for me to send to our company's change management folks.
I would like to have two requirejs tasks - one that uglifies (for sending to CM) and one that doesn't (during development). Is this possible? I tried creating a new task with a different name and grunt yelled at me... should be simple. Is this possible? Are there any reasons not to do this?
Thanks in advance!

Actually it is very simple:
requirejs: {
compile: {
options: {
...
optimize: "none"
}
},
compileForProduction: {
options: {
...
optimize: "uglify2"
}
}
}
(options are same as yours, with any diffs between the two that are required, e.g. optimize)
Run it with:
grunt requirejs:compileForProduction
or in Gruntfile.js:
grunt.registerTask("prod", ["requirejs:compileForProduction"]);
and:
grunt prod

Related

How to prevent grunt-nodemon from restarting all apps

I'm running node on Windows 10. I have three node apps and I want to be able to start them all up with one handy grunt command. Furthermore, I want node to automatically restart if I modify any of the apps.
I'm using a combination of grunt-nodemon and grunt-concurrent for this. The node processes all start up fine.
The problem is that if I modify the code related to any of them they all restart, which takes a long time. How can I make it so that nodemon only restarts the app whose code I actually modified?
var loadGruntTasks = require('load-grunt-tasks')
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concurrent: {
runAll: {
tasks: ['nodemon:app1', 'nodemon:app2', 'nodemon:app3'],
options: {
logConcurrentOutput: true
}
}
},
nodemon: {
app1: {
script: './app1/app.js'
},
app2: {
script: './app2/app.js'
},
app3: {
script: './app3/app.js'
}
}
})
loadGruntTasks(grunt)
grunt.registerTask('default', ['concurrent:runAll'])
}
Update
If I use grunt-watch instead of grunt-nodemon, only the app whose code I modified will restart. The problem is that grunt-watch only knows to run node app.js which gives an error because the app is already running. Is there a way to make grunt-watch kill the node process and restart it?
I think the answer could be fairly simple. Nodemon has an ignore option. For each of your three applications nodemon grunt configurations you can configurate them to ignore the directories of the other applications. That way they only kick off their restart when their own files are changed and not those of other projects. Let me know how that goes. :) Specifics about setting up the ignore section of config can be found in both nodemons documentation and grunt-nodemons documentation.
Patrick Motard's answer made me think about what directory nodemon was running in and how it was observing the files for changes. It appears that since I started grunt inside the parent directory of all the node apps that each nodemon process was looking for changes in all of those directories. So I set the working directory of the nodemon processes to the corresponding directory for each app using the options.cwd setting. That seemed to fix it. Here is the working solution:
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concurrent: {
runAll: {
tasks: ['nodemon:app1', 'nodemon:app2', 'nodemon:app3'],
options: {
logConcurrentOutput: true
}
}
},
nodemon: {
app1: {
script: 'app.js',
options: {
cwd: './app1'
}
},
app2: {
script: 'app.js',
options: {
cwd: './app2'
}
},
app3: {
script: 'app.js',
options: {
cwd: './app3'
}
}
}
})
loadGruntTasks(grunt)
grunt.registerTask('default', ['concurrent:runAll'])
}

How to use require.js and devcode grunt task together in build? (yeoman config)

Hierarchy:
App
.tmp // temp files
app // source files
dist // dist files
So if I put the devcode:build before requirejs:
Files from "app/scripts" are processed and saved into ".tmp/scripts"
Requirejs will be pointed to load the ".tmp/scripts"
Then fails because bower_components are not found at "bower_components"; Of course, because bower_components are located in "app/bower_components"
If I inverse the order:
Requirejs removes the comments and devcode doesn't work
I will remove require.js optimizer and then my build is not ok. Should I pass another uglify over it.
Any better solution? (don't make the pc to copy bower_components all over again, or I might change the position up to the root?)
Thanks
Well I don't need the devcode grunt task becasue requirejs already comes with uglify2 which allows you to have the dist.options.uglify2.compress.global_defs
If you put DEBUG = false then this code will be removed in production mode.
dist: {
options: {
baseUrl : '<%= yeoman.app %>/scripts/',
name : 'main',
mainConfigFile : '<%= yeoman.app %>/scripts/main.js',
out : '.tmp/concat/scripts/main.js',
optimize : 'uglify2',
uglify2: {
//Example of a specialized config. If you are fine
//with the default options, no need to specify
//any of these properties.
output: {
beautify: false
},
compress: {
global_defs: {
DEBUG: false
}
},
warnings : true,
mangle : true
},
}
},

requirejs optimizer doesn't generate '.js' version of the text resource

In my project I use yeoman (1.0.6). In a fresh webapp copy installed requirejs-text plugin to include template.html.
main.js
require.config({
paths: {
jquery: '../bower_components/jquery/jquery',
text: '../bower_components/requirejs-text/text'
}
});
require(['jquery', 'text!../templates.html'], function ($, templates) {
....
After building and optimizing a whole project, I expect to have generated templates.js file instead of templates.html ( added
"optimizeAllPluginResources: true" as described here )
Gruntfile.js ( won't paste all code, just optimization settings )
....
requirejs: {
dist: {
options: {
baseUrl: '<%= yeoman.app %>/scripts',
optimize: 'none',
optimizeAllPluginResources: true,
preserveLicenseComments: false,
useStrict: true,
wrap: true
}
}
},
....
After grunt 'build' task is completed I see that template.html content is in main.js and there is no generated templates.js file
After adding (also have to set in copy task to copy requirejs-text plugin form app to dir folder ):
stubModules: ['text'],
exclude: ['text!../templates.html'],
files are excluded as expected, but there is still no templates.js file. ( get an error as expected: XMLHttpRequest cannot load file:///...../dist/templates.html. Cross origin requests are only supported for HTTP. it works fine with local HTTP )
My question is: What settings am I missing to generate templates.js file with a requirejs optimizer?
p.s. googled, spent all day, tried more than wrote here.
Thank You in Advance

Generating istanbul code coverage reports for jasmine tests run (via grunt) on a browserify bundle in phantomjs

The title says it all really. Despite trawling the internet I haven't found a single example of a solution to this problem.
Here are some near misses
https://github.com/amitayd/grunt-browserify-jasmine-node-example - grunt, browserify and jasmine
https://github.com/gotwarlost/istanbul/issues/59#issuecomment-18799734 - browserify and istanbul
Here is my in-progress code https://github.com/wheresrhys/on-guard/tree/browserify (note it's the 'browserify' branch - Gruntfile.js is a bit of a mess but will tidy it up shortly). My initial investigations using console.log indicate that somehow bundle.src.js is being loaded in the page but when the tests are run (and passed!) the code in bundle.src.js isn't being run, so I have a feeling it might be an aliasing problem... though one that's limited to phantomjs as when I open the specrunner in chrome the code is getting run.
I'm using grunt-browserify + browserify-istanbul + grunt-contrib-jasmine + grunt-template-jasmine-istanbul as solution. This solution has also excluded third party libraries when building source files using browserify.
Show the code first, I'll explain later,
grunt.initConfig({
browserify: {
// build specs using browserify
specs: {
src: ["spec/**/*Spec.js"],
dest: "spec/build/specs.js",
options: {
debug: true
}
},
// build source files using browserify and browserify-istanbul
dev: {
options: {
debug: true,
browserifyOptions: {
standalone: 'abc'
},
transform: [['browserify-istanbul', {
ignore: ['**/node_modules/**'], // ignore third party libs
defaultIgnore: true
}]]
},
src: ['abc.js'],
dest: 'dist/abc.js'
}
},
connect: {
server: {
options: {
port: 7000
}
}
},
// test using jasmine, generate coverage report using istanbul
jasmine: {
coverage: {
src: ['dist/abc.js'],
options: {
junit: {
path: 'bin/junit'
},
host: 'http://localhost:7000/',
specs: 'spec/build/specs.js',
keepRunner: true,
summary: true,
template: require('grunt-template-jasmine-istanbul'),
templateOptions: {
replace: false, // *** this option is very important
coverage: 'bin/coverage/coverage.json',
report: [
{
type: 'html',
options: {
dir: 'spec/coverage/html'
}
}]
}
}
}
}
grunt.registerTask('specs', ['browserify:specs', 'browserify:dev', 'connect', 'jasmine']);
The steps of generating istanbul coverage report can be concluded into three:
Instrument code
Run test
Generate coverage report
In our solution, we use browerify-istanbul in step 1, grunt-contrib-jasmine and runt-template-jasmine-istanbul in step 2 and 3.
browserify-istanbul will let you instrument code in browserify building step, in this way, we can easily ignore third party libs. But the grunt-template-jasmine-istanbul will instrument code again. To avoid this, you can set replace to false in the options.
Refs:
Istanbul steps
broswerify-istanbul
grunt-contrib-jasmine
grunt-template-jasmine-istanbul -- replace option

Configure grunt watch to run Jasmine tests against an app using requirejs

In an attempt to level up my general coding skills... and to learn something new.
I've started attempting to wire up a front end only solution consisting of
Durandal
Jasmine - [added via npm]
Grunt Watch to monitor & run my tests as my code files change - [added via npm]
Feel free to correct me, as this is all based on my experimentation in the last 2 days. Most of this is new to me. My goal is to have something similar as to what angular has with karma.
Now I am aware that that the Durandal project (comes with a custom spec runner, as found in the github solution)
My setup:
gruntfile.js
module.exports = function(grunt) {
var appPath = 'App/viewmodels/*.js';
var testPath = 'Tests/**/*.js';
grunt.initConfig({
jasmine: {
pivotal: {
src: appPath,
options: {
specs: testPath,
template: require('grunt-template-jasmine-requirejs'),
templateOptions: {
requireConfigFile: 'SpecRunner.js'
}
}
}
},
jshint: {
all: [testPath, appPath],
options: {
curly: true
}
},
watch: {
files: [testPath, appPath],
tasks: ['jshint','jasmine']
}
});
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['jshint','jasmine']);
};
SpecRunner.js
require.config({
paths: {
jquery: 'Scripts/jquery-1.9.1',
knockout: 'Scripts/knockout-2.3.0'
},
shim: {
knockout: {
exports: "ko"
}
}
});
When I run grunt, I get a Illegal path or script error: ['plugins/http']
(I've sorted out the ko issue in the screenshot)
Question:
How would i go about setting up my gruntfile to require any dependencies. I'm quite new to require, and I'm not sure how to configure it to make my tests aware of where to find things like 3rd party libraries and other custom js files for that matter
SpecRunner require.config is missing Durandal specific path information. If you set the baseUrl to 'App' then the paths below matches the HTML samples or StarterKit layout. If your layout is different you'd have to adjust this accordingly.
requirejs.config({
paths: {
'text': '../lib/require/text',
'durandal':'../lib/durandal/js',
'plugins' : '../lib/durandal/js/plugins',
'transitions' : '../lib/durandal/js/transitions',
'knockout': '../lib/knockout/knockout-2.3.0',
'bootstrap': '../lib/bootstrap/js/bootstrap',
'jquery': '../lib/jquery/jquery-1.9.1'
}
});

Resources