Pass parameters to processhtml grunt task for updating index.html file - javascript

I am very new to grunt.I have two grunt tasks , one for deploying to dev and one for deploying to test. I wanted to pass the respective deployment url as pararmeter when running the tasks. Also i would like to use this passed parameter value to be updated in my index.html by using processhtml
My deployment tasks:
grunt.registerTask('deploy-dev', ['msdeploy:target1', 'msdeploy:target2']);
grunt.registerTask('deploy-test', ['msdeploy:target3', 'msdeploy:target4']);
//I would like to pass my respective url parameters here , how ?
//how can i use the passed parameters above here to process the html ?
processhtml: {
options: {
data: {
message: grunt.template.today(),
}
},
dist: {
files: {
'dist/index.html': ['index.html']
}
}
}
Index.html:
//i wanted to use the dynamic url value from processhtml here to be updated
<!-- build:template !-->
<script>
var deployUrl = '<%= url%>'
</script>
<!-- /build -->
Is there a better way of doing this ? If i am thinking the right way, how to do it ? Kindly help !

processhtml: {
options: {
data: {
message: grunt.template.today(),
//this will be replaced dynamically based on
//deployment regions
serviceUrl: ''
}
},
dist: {
files: {
'dist/index.html': ['index.html']
}
}
}
grunt.registerTask('deploy-dev', function () {
grunt.config.set('processhtml.options.data.serviceUrl', "http://server1/api");
//run the processhtml with the new parameter
grunt.task.run('processhtml');
//call the deployment task
grunt.task.run('msdeploy:server1');
});
Index.html file changes:
<!-- build:template !-->
<script>
var buildDateTime = '<%= message %>'
var serviceBase = '<%= serviceUrl %>'
</script>
<!-- /build -->

Related

gulp-task output in console is not printing expected result

I have the following gulp task which inserts .css and .js files in the html file:
gulp.task('inject', function () {
log('Injecting the JS and CSS files into index.html');
var wiredep = require('wiredep').stream;
var options = config.getWiredepDefaultOptions();
return gulp.src(config.index)
.pipe(wiredep(options))
.pipe($.inject(gulp.src(config.customFiles), {ignorePath: options.ignorePath}))
.pipe(gulp.dest(config.client));
});
and my gulp.config.js:
module.exports = function () {
var client = './public';
var config = {
allJS: [
'*.js',
'public/js/*.js',
'public/js/**/*.js'
],
client: client,
index: client + '/index.html',
customFiles: [
'./public/css/*.css',
'./public/js/*.js',
'./public/js/**/*.js'
],
bower: {
json: require('./bower.json'),
directory: './public/lib',
ignorePath: '/public/'
},
};
config.getWiredepDefaultOptions = function () {
var options = {
bowerJson: config.bower.json,
directory: config.bower.directory,
ignorePath: config.bower.ignorePath
};
return options;
};
return config;
};
This works as expected, but when I run the task I get this:
It always says gulp-inject 3 files into index.html, even though no new files was added.
Is there something wrong with my gulp file?
Well if you are using gulp-inject this is what I found.
If you look at the code in gulp-inject you can see it just spits out the file count unless it gets opt.quiet set. I didn't see a option in the docs for this setting but if you look at the tests it shows an example it being used.
Enabling quiet mode link line 505
inject(sources, {quiet: true});
Source where it generates the log statement. link line 109
function getNewContent(target, collection, opt) {
var logger = opt.quiet ? noop : function (filesCount) {
if (filesCount) {
log(cyan(filesCount) + ' files into ' + magenta(target.relative) + '.');
} else {
log('Nothing to inject into ' + magenta(target.relative) + '.');
}
};

Grunt-scaffold after() function access to prompt answers

The docs for the NPM package grunt-scaffold lacked any information really on its after() property/function.. I have a grunt file which creates a new directory for a new script and copies boilerplate files into it from the designated template folder.. The desire is to finish the grunt scaffold:new_script command and have it log out the location of the newly generated folder.
Gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
scaffold: {
new_script: {
options: {
questions: [{
name: 'script_name',
type: 'input',
message: 'Script name, catterpillar_case?(e.g. \'new_script\'):'
}],
template: {
"scripts/etl_template/": "scripts/{{script_name}}/",
},
after: function(){
console.log("New script generated in new folder scripts/{{script_name}}")
}
}
}
}
});
grunt.loadNpmTasks('grunt-scaffold');
grunt.registerTask('default', ['scaffold']);
};
However, the ouput is
-bash-4.1$ grunt scaffold:new_script
Running "scaffold:new_script" (scaffold) task
? Script name, catterpillar_case?(e.g. 'new_script'): test_grunt
New script generated in new folder scripts/{{script_name}}
Done.
This did not do the string replacing as it did when it created the scripts/test_grunt folder! As you can see the documentation almost doesn't exist for that after() functionality, and I'm wondering if I can use javascript"system argume
An example was not given in the documentation for the after() function, but if you use the same result parameter as in the example given for filter(), you can access the answer values via their names.
Gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
scaffold: {
new_script: {
options: {
questions: [{
name: 'script_name',
type: 'input',
message: 'Script name, catterpillar_case?(e.g. \'new_script\'):'
}],
template: {
"scripts/etl_template/": "scripts/{{script_name}}/",
},
after: function(result){
console.log("New script generated in new folder scripts/" + result.script_name)
}
}
}
}
});
grunt.loadNpmTasks('grunt-scaffold');
grunt.registerTask('default', ['scaffold']);
};
Output
-bash-4.1$ grunt scaffold:new_script
Running "scaffold:new_script" (scaffold) task
? Script name, catterpillar_case?(e.g. 'new_script'): test_grunt
New script generated in new folder scripts/test_grunt
Done.

GruntJS glob as source

I have a huge array like
[ { src:
[ './src/branding/appLogo/template.hbs',
'./src/buttons/append/template.hbs',
'./src/buttons/button/template.hbs',
'./src/buttons/clean/template.hbs',
'./src/buttons/clear/template.hbs',
'./src/buttons/danger/template.hbs',
'./src/buttons/default/template.hbs',
'./src/buttons/disabled/template.hbs',
'./src/buttons/large/template.hbs',
'./src/buttons/link/template.hbs',
'./src/buttons/primary/template.hbs',
'./src/buttons/small/template.hbs',
'./src/buttons/success/template.hbs',
'./src/documentation/technology-overview/template.hbs',
'./src/forms/checkbox/template.hbs',
'./src/forms/fieldAppend/template.hbs',
'./src/forms/fieldDefault/template.hbs',
'./src/forms/fieldError/template.hbs',
'./src/forms/fieldPrepend/template.hbs',
'./src/forms/fieldPrependAppend/template.hbs',
'./src/forms/radioButton/template.hbs',
'./src/forms/select/template.hbs',
'./src/forms/textarea/template.hbs',
'./src/icons/appSwitch/template.hbs',
'./src/modules/alerts/template.hbs',
'./src/modules/attributions/template.hbs',
'./src/modules/avatar/template.hbs',
'./src/modules/beacon/template.hbs',
'./src/modules/d3DonutChart/template.hbs',
'./src/navigation/appSwitcher/template.hbs',
'./src/navigation/avatarDropdown/template.hbs',
'./src/navigation/contextMenu/template.hbs',
'./src/navigation/headerMenu/template.hbs',
'./src/navigation/paginate/template.hbs',
'./src/prototypes/home/template.hbs',
'./src/structures/form/template.hbs',
'./src/structures/header/template.hbs',
'./src/typography/blockquote/template.hbs',
'./src/typography/floats/template.hbs',
'./src/typography/headers/template.hbs',
'./src/typography/hidden/template.hbs',
'./src/typography/hr/template.hbs',
'./src/typography/hrText/template.hbs',
'./src/typography/lists/template.hbs',
'./src/typography/paragraph/template.hbs',
'./src/typography/pre/template.hbs',
'./src/typography/table/template.hbs',
'./src/typography/tags/template.hbs',
'./src/utilities/extends/template.hbs',
'./src/utilities/keyframes/template.hbs',
'./src/utilities/mixins/template.hbs',
'./src/utilities/svgFilterPieShrink/template.hbs',
'./src/utilities/svgFilterSubtleDropShadow/template.hbs' ],
dest: './build/scripts/handlebars.js' } ]
I want to render all those handlebars templates and they should all end up in a single file.
module.exports = (grunt) ->
config = grunt.file.readJSON("config.json")
hbsGlob = ''
grunt.task.loadTasks('./tasks')
grunt.option('config', config)
grunt.initConfig
pkg: grunt.file.readJSON("package.json")
handlebars:
options:
namespace: 'Guide'
processName: (path) ->
return path.replace('.js', '').replace('/', '.') + '.template'
guide:
files:
#hbsGlob
grunt.registerTask 'etch-scripts', =>
glob = grunt.option('filteredGlob')
glob.push "!./src/**/*.{md,js,json}"
options =
rename: (dest, matchedSrcPath, options) ->
return dest
#hbsGlob = grunt.file.expandMapping(glob, config.build + '/scripts/handlebars.js', options)
grunt.task.run 'handlebars:guide'
grunt.loadNpmTasks('grunt-contrib-handlebars');
The only output I am getting is
Running "handlebars:guide" (handlebars) task
>> 0 files created.
Done, without errors.
Any idea what is going wrong so I can use that glob as the src/dest?
After lots of research on this, I found a slight alternative that ended up working perfectly!
After setting the hbsGlob variable, I added that var to a Grunt config grunt.config.set('hbsGlob', #hbsGlob)
Then in the handlebars:guide task I set it to
guide:
files: '<%= hbsGlob %>'
And everything built out perfectly!
Edit -- Source: https://stackoverflow.com/a/14780870/399742

Register Assemble Handlebars Helpers

I am trying to do something that seems relatively simple from the Assemble docs and other repos I've looked at but for some reason I'm having a problem registering my Handlebars helpers. The helper is in helpers > helper-classgrid.js
module.exports.register = function (Handlebars, options, params) {
Handlebars.register('classgrid', function (index, options) {
gridclass: function (index, options) {
if (index === 0 || index % 4 === 0) {
return options.fn(this);
}
return options.inverse(this);
};
};
My gruntfile where config.helpers = helpers:
assemble: {
options: {
layoutdir: '<%= config.guts %>/templates/layouts/',
assetsDir: '<%= grunt.config.get("assets_dir") %>',
environmentIsProduction: '<%= grunt.config.get("environmentIsProduction") %>',
environmentIsDev: '<%= grunt.config.get("environmentIsDev") %>',
data: ['<%= config.content %>/**/*.json', '<%= grunt.config.get("environmentData") %>'],
helpers: ['<%= config.helpers %>/helper-*.js']
},
}
Template code:
{{#classgrid #index}}
// do something here
{{/classgrid}}
Now when I implement my helper in my Handlerbars template and run the grunt task containing the assemble task I get the error
Warning: Missing helper: 'classgrid' Use --force to continue.
I'm not sure what I've done wrong or if I have to create a separate NPM package for my helpers which it seems to suggest in the assemble docs. I've looked at these 2 repos which seem to be doing what I'm trying to do
https://github.com/buildingblocks/bb-prototype-website/blob/master/Gruntfile.js
https://github.com/ghost-town/layouts-example/blob/master/Gruntfile.js#L33
Not sure if this was just a copy/paste issue, but the code above doesn't look correct... here's what should work:
module.exports.register = function (Handlebars, opts, params) {
Handlebars.registerHelper('classgrid', function (index, options) {
if (index === 0 || index % 4 === 0) {
return options.fn(this);
}
return options.inverse(this);
});
};
I'll try to create a test project to make sure this is working.
Edit: After creating a test project, I see that you were using Handlebars.register instead of Handlebars.registerHelper. I've updated the code to a working solution. Hope this helps.

Loading external file from Karma/Jasmine test

I'm trying to accomplish a Jasmine test (using Karma and IntelliJ 13) to validate JSON files. Ideally, my test would simply load a JSON file into a data object, then let me parse through to check for valid formatting and data. I don't need to validate functions before or after, nor do I need to test against a server.
My basic setup is like this:
it("should load an external file", function(){
var asyncCallComplete, result,
_this = this;
// asyncCallComplete is set to true when the ajax call is complete
asyncCallComplete = false;
// result stores the result of the successful ajax call
result = null;
// SECTION 1 - call asynchronous function
runs(function() {
return $.ajax('/test/config.json', {
type: 'GET',
success: function(data) {
asyncCallComplete = true;
result = data;
},
error: function() {
asyncCallComplete = true;
}
});
});
// SECTION 2 - wait for the asynchronous call to complete
waitsFor(function() {
return asyncCallComplete !== false;
}, "async to complete");
// SECTION 3 - perform tests
return runs(function() {
return expect(result).not.toBeNull();
});
}
The problem is that no matter what path I use, I get a 404 error and the file won't load. I've tried loading an external JSON result from a remote server using this test service:
http://date.jsontest.com/
And this works.
My test file is named /test/mySpec.js and my karma.conf.js file is on the root. I have moved around the JSON file to all of these locations with no luck. What am I doing wrong?
UPDATE WITH ANSWER:
Per the answer below, I added this to my karma.conf.js:
// fixtures
{ pattern: 'test/*.json',
watched: true,
served: true,
included: false
}
Then, I wrote my test this way:
var json:any;
it("should load a fixture", function () {
jasmine.getFixtures().fixturesPath = "base/test/"
var f = readFixtures("registration.json");
json = JSON.parse(f);
expect(json).toBeDefined();
})
it("should have a title", function () {
expect(json.title).toNotBe(null);
})
etc...
And it passes.
Are you serving the JSON file via karma.config.js?
You can serve JSON files via fixture:
files: [
// angular
'angular.min.js',
'angular-route.js',
'angular-mocks.js',
// jasmine jquery helper
'jquery-1.10.2.min.js',
'jasmine-jquery.js',
// app
'../../public/js/app.js',
// tests
'*-spec.js',
// JSON fixture
{ pattern: '/test/*.json',
watched: true,
served: true,
included: false }
],
Serving JSON via the fixture is the easiest but because of our setup we couldn't do that easily so I wrote an alternative helper function:
Install
bower install karma-read-json
Usage
Put karma-read-json.js in your Karma files, Example:
files = [
...
'bower_components/karma-read-json/karma-read-json.js',
...
]
Make sure your JSON is being served by Karma, Example:
files = [
...
{pattern: 'json/**/*.json', included: false},
...
]
Use the readJSON function in your tests. Example:
var valid_respond = readJSON('json/foobar.json');
$httpBackend.whenGET(/.*/).respond(valid_respond);
If you are trying to load a HTML file and want to avoid using jasmine-jquery, you may take advantage of the karma-ng-html2js-preprocessor.
In your karma.conf.js :
// generate js files from html templates
preprocessors: {
'resources/*.html': 'ng-html2js'
},
files: [
...
'resources/*.html'
],
plugins: [
...
'karma-ng-html2js-preprocessor'
],
In your jasmine spec :
beforeEach(module('resources/fragment.html'));
var $templateCache;
beforeEach(inject(function (_$templateCache_) {
$templateCache = _$templateCache_;
}));
describe('some test', function () {
it('should do something', function () {
// --> load the fragment.html content from the template cache <--
var fragment = $templateCache.get('resources/fragment.html');
expect(fragment).toBe(...);
});
});
Have you tried simply requiring the json file and storing it as a global variable in your test?
I'm developing an Angular2 project right now (using the Angular CLI), and with this setup it works:
// On the very beginning of the file
let mockConfig = require('./test/config.json');

Categories

Resources