grunt load dynamic JSON file - javascript

Is it possible to load a JSON file from a dynamic source? I want to do some localisation
grunt.file.readJSON('src/locales/<%= grunt.task.current.args[0] %>/i18n.json');
A fuller example of the Gruntfile looks like:
module.exports = function(grunt) {
var i18n = {
locales: ['en', 'fr', 'de', 'es'],
default: 'en',
replacements: function(locale){
var content = grunt.file.readJSON('src/locales/<%= grunt.task.current.args[0] %>/i18n.json');
var arr = [];
for(i in content){
var replacement = {
from: i,
to: content[i].value
};
arr.push(replacement);
}
return arr;
}
};
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
replace: {
build: {
src: ['local/en/**/*.html'], // source files array (supports minimatch)
dest: 'local/<%= grunt.task.current.args[0] %>/', // destination directory or file
replacements: i18n.replacements('<%= grunt.task.current.args[0] %>')
}
},
While registering the task looks like:
grunt.registerTask('localise', function(){
var tasks = [];
for(i in i18n.locales){
if(i18n.locales[i] !== i18n.default){
tasks.push('replace:build:' + i18n.locales[i]);
}
}
grunt.task.run(tasks);
});
Everything works as I'd hoped except loading the JSON to actually do the replacements.
I've also tried:
grunt.file.readJSON('src/locales/'+locale+'/i18n.json');
which didn't work either, leaving me a little stumped.
Anyone able to help?
Thanks

Try:
'src/locales/' + grunt.task.current.args[0] + '/i18n.json'

Ok, I got it working after much trial and error:
I updated the function returning the data to:
var i18n = {
locales: ['en', 'fr', 'de', 'es'],
default: 'en',
replacements: function(locale){
var content = grunt.file.readJSON('src/locales/'+ locale +'/i18n.json');
var arr = [{from: "/" + locale, to: "/en"}, {from: "Test", to: locale}];
for(i in content){
var replacement = {
from: i,
to: content[i].value
};
arr.push(replacement);
}
console.log(arr);
return arr;
}
};
Then set an empty array in the default task:
replace: {
build: {
src: ['local/en/**/*.html'], // source files array (supports minimatch)
dest: 'local/<%= grunt.task.current.args[0] %>/', // destination directory or file
replacements: []
}
},
Which is updated using it's own task
grunt.registerTask('updateConf', function(locale){
var content = i18n.replacements(locale);
grunt.config('replace.build.replacements', content);
});
That is run just before the replace task:
grunt.registerTask('localise', function(){
var tasks = [];
for(i in i18n.locales){
if(i18n.locales[i] !== i18n.default){
tasks.push('updateConf:' + i18n.locales[i]);
tasks.push('replace:build:' + i18n.locales[i]);
}
}
grunt.task.run(tasks);
});
Giving the right output. Probably not the most elegant of solutions but it works!

Related

Angular 2 quickstart demo doesn't work

I am new to Angular 2 and to get started, I download Quickstart project from the official website.
But it shows me the following error in console:
GET
http://localhost:3000/node_modules/#angular/platf...-dynamic/bundles/platform-browser-dynamic.umd.js
304 Not Modified 87ms zone.js (line 2019) GET
http://localhost:3000/systemjs-angular-loader.js 404 Not Found
2ms zone.js (line 2019)
"NetworkError: 404 Not Found -
http://localhost:3000/systemjs-angular-loader.js" systemj...ader.js
Unhandled Promise rejection: Permission denied to access property
"then" ; Zone: ; Task: Promise.then ; Value: Error: Permission
denied to access property "then"
resolvePromise#http://localhost:3000/node_modules/zone.js/dist/zone.js:622:21
scheduleResolveOrReject/<#http://localhost:3000/node_modules/zone.js/dist/zone.js:716:17
ZoneDelegate.prototype.invokeTask#http://localhost:3000/node_modules/zone.js/dist/zone.js:367:17
Zone.prototype.runTask#http://localhost:3000/node_modules/zone.js/dist/zone.js:166:28
drainMicroTaskQueue#http://localhost:3000/node_modules/zone.js/dist/zone.js:546:25
ZoneTask/this.invoke#http://localhost:3000/node_modules/zone.js/dist/zone.js:424:25
change your systemjs.config.js with this systemjs.config.js
(function (global) {
System.config({
map: {
'rxjs': 'node_modules/rxjs',
'#angular': 'node_modules/#angular',
'app': './app',
'angular2-in-memory-web-api' : 'node_modules/angular2-in-memory-web-api'
},
packages: {
'app': {
main: 'main.js',
defaultExtension: 'js'
},
'#angular/platform-browser': {
main: 'bundles/platform-browser.umd.js'
},
'#angular/core': {
main: 'bundles/core.umd.js'
},
'#angular/http': {
main: 'bundles/http.umd.js'
},
'#angular/compiler': {
main: 'bundles/compiler.umd.js'
},
'#angular/compiler-cli': {
main: 'index.js'
},
'#angular/router': {
main: 'bundles/router.umd.js'
},
'#angular/upgrade': {
main: 'bundles/upgrade.umd.js'
},
'#angular/forms': {
main: 'bundles/forms.umd.js'
},
'#angular/common': {
main: 'bundles/common.umd.js',
defaultExtension: 'js'
},
'#angular/platform-browser-dynamic': {
main: 'bundles/platform-browser-dynamic.umd.js'
},
'#angular/platform-server': {
main: 'bundles/platform-server.umd.js'
},
'rxjs': {
defaultExtension: 'js'
},
'angular2-in-memory-web-api': {
main: './index.js',
defaultExtension: 'js'
}
}
});
})(this);
It seems that Angular.io team included systemjs-angular-loader.js into the plunker links, however forgot to include the file into downloadable projects.
Please add systemjs-angular-loader.js to the same level as systemjs.config.js
var templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*)/gm;
var stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g;
var stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;
module.exports.translate = function(load){
var url = new URL(load.address);
var basePathParts = url.pathname.split('/');
if (url.href.indexOf('plnkr') != -1) {
basePathParts.shift();
basePathParts.shift();
}
basePathParts.pop();
var basePath = basePathParts.join('/');
load.source = load.source
.replace(templateUrlRegex, function(match, quote, url){
let resolvedUrl = url;
if (url.startsWith('.')) {
resolvedUrl = basePath + url.substr(1);
}
return `templateUrl: '${resolvedUrl}'`;
})
.replace(stylesRegex, function(match, relativeUrls) {
var urls = [];
while ((match = stringRegex.exec(relativeUrls)) !== null) {
if (match[2].startsWith('.')) {
urls.push(`'${basePath.substr(1)}${match[2].substr(1)}'`);
} else {
urls.push(`'${match[2]}'`);
}
}
return "styleUrls: [" + urls.join(', ') + "]";
});
return load;
};
Code taken from here:
https://angular.io/resources/live-examples/forms/ts/eplnkr.html
systemjs-angular-loader.js is a new module mentioned in the Change Log for March 13, https://angular.io/docs/ts/latest/guide/change-log.html, but I have yet to find it.
The issue is pointed out in the first lines of your error log:
GET http://localhost:3000/systemjs-angular-loader.js 404 Not Found 2ms zone.js (line 2019)
Which means systemjs-angular-loader.js file is missing in your project.
As #TimFogarty mentioned in his answer, systemjs-angular-loader.js is a new module added to Angular 4.0.
Since the official docs still don't shed light on what should be inside the systemjs-angular-loader.js and even Angular-CLI doesn't generate it, I believe the only option is to take it from the official Angular Quickstart project.
Just for reference, here is its current version:
var templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*)/gm;
var stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g;
var stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;
module.exports.translate = function(load){
if (load.source.indexOf('moduleId') != -1) return load;
var url = document.createElement('a');
url.href = load.address;
var basePathParts = url.pathname.split('/');
basePathParts.pop();
var basePath = basePathParts.join('/');
var baseHref = document.createElement('a');
baseHref.href = this.baseURL;
baseHref = baseHref.pathname;
if (!baseHref.startsWith('/base/')) { // it is not karma
basePath = basePath.replace(baseHref, '');
}
load.source = load.source
.replace(templateUrlRegex, function(match, quote, url){
var resolvedUrl = url;
if (url.startsWith('.')) {
resolvedUrl = basePath + url.substr(1);
}
return 'templateUrl: "' + resolvedUrl + '"';
})
.replace(stylesRegex, function(match, relativeUrls) {
var urls = [];
while ((match = stringRegex.exec(relativeUrls)) !== null) {
if (match[2].startsWith('.')) {
urls.push('"' + basePath + match[2].substr(1) + '"');
} else {
urls.push('"' + match[2] + '"');
}
}
return "styleUrls: [" + urls.join(', ') + "]";
});
return load;
};
I am using Angular 4.3.2, a recent but not the latest version, and I do not have systemjs-angular-loader.js in my package.json file. I do not get the OP's 404 error. Does this mean systemjs-angular-loader.js is now buried somewhere in version 4.x.y?
On the other hand, if I remove moduleId: module.id from the #Component in my app.component.ts, the page no longer loads. It feels like some code change has been made, hinted at in the documentation changelog https://devdocs.io/angular~2/guide/change-log, but not described in Angular Changelog https://github.com/angular/angular/blob/master/CHANGELOG.md or Getting Started documentation. There are no examples (before -> after) to be found in Angular documentation.
The answer needs to come in official Angular code documentation - with before -> after examples. Then reference it here.

gruntjs - how to list filenames and data attributes of those filenames in an HTML file?

I am creating a lot of HTML files that will be used as the design guideline for a development project. An HTML file will include the following HTML tags:
<title> Design pattern 001 </title>
<meta data-details="This design should show the basic homepage" />
<meta data-status="Approved" />
All of these files sit in a directory:
/designs/design-pattern-001.html
...
/designs/design-pattern-100.html
I want to run a grunt task that will create a separate index.html with the following syntax:
<table>
<tr>
<td> Aprooved</td>
<td> Design pattern 001 </td>
<td> This design should show the basic homepage </td>
</tr>
....
</table>
My development team will then use index.html
I tried the solution here: How do I generate a list of files in html, using a grunt task? but this only gets me the filename, not any of the data attributes within each respective HTML.
Is the only other solution to use jQuery (or JavaScript) to get this for each respective file like the solution here: Get HTML code of a local HTML file in Javascript ?
This can be done via a grunt custom task. I've gone ahead and built an example project on github using your outlined requirements above.
I was able to do it using the following node modules:
xmldom and xpath to parse the html files
pug to create the generated html from a template
Please check out the github project but here is most of the important code:
Grunt file ( in root of project ):
Defines custom tasks options
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
parseAndIndexHtmlFiles : {
options : {
output: "index.html",
directoryToParse: "design",
jadeTemplate: "index.jade",
parseHtmlTags: ["title"],
parseAttributes: ["data-details", "data-status"]
}
}
});
grunt.loadTasks('tasks');
grunt.registerTask('default', [ "parseAndIndexHtmlFiles" ]);
};
Custom task file ( in tasks folder of project ) /tasks/parseDesignHtml.js:
var DOMParser = require('xmldom').DOMParser;
var xpath = require('xpath');
var Promise = require("bluebird");
var pug = require('pug');
var tidy = require('htmltidy').tidy;
var fs = Promise.promisifyAll(require("fs"));
var options, done, globalGrunt = null;
var fileIndex = [];
module.exports = function(grunt) {
globalGrunt = grunt;
grunt.registerTask('parseAndIndexHtmlFiles', function () {
done = this.async();
options = this.options({
output : "",
directoryToParse : "",
jadeTemplate : "",
parseHtmlTags : [ ],
parseAttributes : [ ]
});
parseHtmlFiles(options.directoryToParse);
});
};
function parseHtmlFiles(directory) {
fs.readdirAsync(directory).map(function (filename) {
if (filename.match(/.html$/)) {
return readFile(directory + "/" + filename);
}
}).then(function (results) {
var contents = [];
for(var i = 0; i < results.length; i++){
if(results[i]){
contents.push(results[i]);
}
}
var html = pug.renderFile(options.jadeTemplate , {
files : contents
});
tidy(html, {
indent: true
}, function (err, result) {
if (err) {
globalGrunt.fail.fatal(err);
}
fs.writeFile(options.output, result, function (err) {
if (err) {
globalGrunt.fail.fatal(err);
}
done();
});
});
});
}
function readFile(filename) {
var promise = Promise.pending();
fs.readFile(filename, function (err, data) {
if (err) {
promise.reject(err);
} else if (data) {
var doc = new DOMParser().parseFromString(data.toString(), "text/html");
var params = parseDocument(doc);
promise.resolve(new IndexedFile(filename, params));
} else {
promise.reject("No Data");
}
});
return promise.promise;
}
function parseDocument(doc) {
var params = {
tags : {},
attributes : {}
};
options.parseHtmlTags.forEach(function (tag) {
var tags = doc.getElementsByTagName(tag);
if (tags.length > 0) {
params.tags[tag] = tags[0].firstChild.data;
}
});
options.parseAttributes.forEach(function (attrName) {
var attr = xpath.select("//#" + attrName, doc);
if (attr.length > 0) {
params.attributes[attrName] = attr[0].nodeValue;
}
});
return params;
}
function IndexedFile(path, parameters) {
this.path = path;
this.parameters = parameters;
}
Template file ( in root of project ) /index.jade:
doctype html
html(lang="en")
head
title="Stackoverflow Question 40011711"
body
table
- files.forEach(function (item) {
tr
td
a(href=item.path)=item.parameters.tags["title"]
td=item.parameters.attributes["data-status"]
td=item.parameters.attributes["data-details"]
- })

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) + '.');
}
};

Can I use a Gulp task with multiple sources and multiple destinations?

I have the following in my gulpfile.js:
var sass_paths = [
'./httpdocs-site1/media/sass/**/*.scss',
'./httpdocs-site2/media/sass/**/*.scss',
'./httpdocs-site3/media/sass/**/*.scss'
];
gulp.task('sass', function() {
return gulp.src(sass_paths)
.pipe(sass({errLogToConsole: true}))
.pipe(autoprefixer('last 4 version'))
.pipe(minifyCSS({keepBreaks:true}))
.pipe(rename({ suffix: '.min'}))
.pipe(gulp.dest(???));
});
I'm wanting to output my minified css files to the following paths:
./httpdocs-site1/media/css
./httpdocs-site2/media/css
./httpdocs-site3/media/css
Am I misunderstanding how to use sources/destinations? Or am I trying to accomplish too much in a single task?
Edit: Updated output paths to corresponding site directories.
I guess that the running tasks per folder recipe may help.
Update
Following the ideas in the recipe, and oversimplifying your sample just to give the idea, this can be a solution:
var gulp = require('gulp'),
path = require('path'),
merge = require('merge-stream');
var folders = ['httpdocs-site1', 'httpdocs-site2', 'httpdocs-site3'];
gulp.task('default', function(){
var tasks = folders.map(function(element){
return gulp.src(element + '/media/sass/**/*.scss', {base: element + '/media/sass'})
// ... other steps ...
.pipe(gulp.dest(element + '/media/css'));
});
return merge(tasks);
});
you are going to want to use merge streams if you would like to use multiple srcs but you can have multiple destinations inside of the same one. Here is an example.
var merge = require('merge-stream');
gulp.task('sass', function() {
var firstPath = gulp.src(sass_paths[0])
.pipe(sass({errLogToConsole: true}))
.pipe(autoprefixer('last 4 version'))
.pipe(minifyCSS({keepBreaks:true}))
.pipe(rename({ suffix: '.min'}))
.pipe(gulp.dest('./httpdocs-site1/media/css'))
.pipe(gulp.dest('./httpdocs-site2/media/css'));
var secondPath = gulp.src(sass_paths[1])
.pipe(sass({errLogToConsole: true}))
.pipe(autoprefixer('last 4 version'))
.pipe(minifyCSS({keepBreaks:true}))
.pipe(rename({ suffix: '.min'}))
.pipe(gulp.dest('./httpdocs-site1/media/css'))
.pipe(gulp.dest('./httpdocs-site2/media/css'));
return merge(firstPath, secondPath);
});
I assumed you wanted different paths piped here so there is site1 and site2, but you can do this to as many places as needed. Also you can specify a dest prior to any of the steps if, for example, you wanted to have one dest that had the .min file and one that didn't.
You can use gulp-rename to modify where files will be written.
gulp.task('sass', function() {
return gulp.src(sass_paths, { base: '.' })
.pipe(sass({errLogToConsole: true}))
.pipe(autoprefixer('last 4 version'))
.pipe(minifyCSS({keepBreaks:true}))
.pipe(rename(function(path) {
path.dirname = path.dirname.replace('/sass', '/css');
path.extname = '.min.css';
}))
.pipe(gulp.dest('.'));
});
Important bit: use base option in gulp.src.
For the ones that ask themselves how can they deal with common/specifics css files (works the same for scripts), here is a possible output to tackle this problem :
var gulp = require('gulp');
var concat = require('gulp-concat');
var css = require('gulp-clean-css');
var sheets = [
{ src : 'public/css/home/*', name : 'home.min', dest : 'public/css/compressed' },
{ src : 'public/css/about/*', name : 'about.min', dest : 'public/css/compressed' }
];
var common = {
'materialize' : 'public/assets/materialize/css/materialize.css'
};
gulp.task('css', function() {
sheets.map(function(file) {
return gulp.src([
common.materialize,
file.src + '.css',
file.src + '.scss',
file.src + '.less'
])
.pipe( concat(file.name + '.css') )
.pipe( css() )
.pipe( gulp.dest(file.dest) )
});
});
All you have to do now is to add your sheets as the object notation is constructed.
If you have additionnal commons scripts, you can map them by name on the object common, then add them after materialize for this example, but before the file.src + '.css' as you may want to override the common files with your customs files.
Note that in the src attribute you can also put path like this :
'public/css/**/*.css'
to scope an entire descendence.
I had success without needing anything extra, a solution very similar to Anwar Nairi's
const p = {
dashboard: {
css: {
orig: ['public/dashboard/scss/style.scss', 'public/dashboard/styles/*.css'],
dest: 'public/dashboard/css/',
},
},
public: {
css: {
orig: ['public/styles/custom.scss', 'public/styles/*.css'],
dest: 'public/css/',
},
js: {
orig: ['public/javascript/*.js'],
dest: 'public/js/',
},
},
};
gulp.task('default', function(done) {
Object.keys(p).forEach(val => {
// 'val' will go two rounds, as 'dashboard' and as 'public'
return gulp
.src(p[val].css.orig)
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(autoPrefixer())
.pipe(cssComb())
.pipe(cmq({ log: true }))
.pipe(concat('main.css'))
.pipe(cleanCss())
.pipe(sourcemaps.write())
.pipe(gulp.dest(p[val].css.dest))
.pipe(reload({ stream: true }));
});
done(); // <-- to avoid async problems using gulp 4
});
Multiple sources with multiple destinations on gulp without using any extra plugins just doing concatenation on each js and css. Below code works for me. Please try it out.
const gulp = require('gulp');
const concat = require('gulp-concat');
function task(done) {
var theme = {
minifiedCss: {
common: {
src : ['./app/css/**/*.min.css', '!./app/css/semantic.min.css'],
name : 'minified-bundle.css',
dest : './web/bundles/css/'
}
},
themeCss:{
common: {
src : ['./app/css/style.css', './app/css/responsive.css'],
name : 'theme-bundle.css',
dest : './web/bundles/css/'
}
},
themeJs: {
common: {
src: ['./app/js/jquery-2.1.1.js', './app/js/bootstrap.js'],
name: 'theme-bundle.js',
dest: './web/_themes/js/'
}
}
}
Object.keys(theme).map(function(key, index) {
return gulp.src(theme[key].common.src)
.pipe( concat(theme[key].common.name) )
.pipe(gulp.dest(theme[key].common.dest));
});
done();
}
exports.task = task;
Using gulp-if helps me a lot.
The gulp-if first argument. is the gulp-match second argument condition
gulp-if can be found in gulp-if
import {task, src, dest} from 'gulp';
import VinylFile = require("vinyl");
const gulpif = require('gulp-if');
src(['foo/*/**/*.md', 'bar/*.md'])
.pipe(gulpif((file: VinylFile) => /foo\/$/.test(file.base), dest('dist/docs/overview')))
.pipe(gulpif((file: VinylFile) => /bar\/$/.test(file.base), dest('dist/docs/guides')))
});
I think we should create 1 temporary folder for containing all these files. Then gulp.src point to this folder
The destination will have the same directory structure as the source.

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

Categories

Resources