Create Your Own Yeoman Generator
Join the DZone community and get the full member experience.
Join For Freesometimes you may have some specific setup that you like to use in your own projects. because you don’t want to reinvent your own wheel in every project, it makes sense to abstract all the boilerplate into your own generator. in this situation you can build your own yeoman generator. this will kick-start your projects.
in this article, we will be building a yeoman generator for generating a single page application. this generated scaffold contains angularjs and/or jquery, sass, bootstrap and 'modernizr'. for testing you can choose between the mocha framework or jasmine.
getting set up
first of all you need to install node.js . you can get the installation from here . besides that, we will need to have yeoman and bower installed as well as the generator ( yo ) for creating generators. you can accomplish this via the following commands to npm :
npm install -g bower
npm install -g yo
npm install -g generator-generator
npm install -g yeoman/generator-mocha
and finally install git
first, create a folder within which you'll write your generator. this folder must be named generator-name (where name is the name of your generator). this is important, as yeoman relies on the file system to find available generators.
mkdir generator-myapp
cd generator-myapp
and generate in this folder your basic generator:
yo generator
this will start the generator and ask you some questions like the project name and your github account. i am going to name my generator: myapp .
the file structure
these are the files generated by the command, it will all make sense in just a moment.
the first couple of files are dotfiles for various things like git and jshint, we have a package.json file for the generator itself, a readme file and a folder for tests.
the .yo-rc.json is very important to locate the root of the project.
the generators folder holds each sub-generator. each folder has the same name as the sub-generator name. in our case we have one (default) generator app , that is called with command: yo myapp . each sub-generator has an index.js file, that contains the entry point for the generator, and a templates folder that contains the template files for the boilerplate (for generating the actual scaffolding).
the test- folder holds the tests for the yeoman generator.
now you have a default generator ready. so before modifying it to add our custom features, we will test this base generator. since you’re developing the generator locally, and haven’t published it yet, you have to symlink your local module as a global module, using npm. why?
this is handy for installing your own stuff, so that you can work on it and test it iteratively without having to continually rebuild. run this command in your generators root directory (the root folder is where you can find the: .yo-rc.json ):
npm link
make a new folder on your filesystem (i.e. outputfolder) for your application and test your generator. you can scaffold your very own web app now:
mkdir testmyapp
cd testmyapp
yo myapp
a new scaffolding will be generated in the outputfolder: testmyapp
how to script your generator
yeoman generated a base structure for our generator, now we will check how to customize it and add our own features in the generator by the following steps:
- setup the actual generator object
- initializing the generator
- getting user inputs
- options and arguments
- adding custom templates
- write the generator specific files
- install npm and bower
- scaffold your app
- unittest
1. setup the actual generator object
the index.js file needs to export the actual generator object (myappgenerator) which will get run by yeoman. i am going to clear everything inside the actual generator so we can start from scratch, here is what the file should look like after that:
'use strict';
var fs = require('fs');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');
var wiredep = require('wiredep');
var myappgenerator = yeoman.generators.base.extend({
});
module.exports = myappgenerator;
a yeoman generator can extend from the base generator. all this code in the index.js is doing is creating the generator object: ‘myappgenerator’ and exporting it. yeoman will pick up the exported object and run it. the way it runs, is by first calling the constructor method and then it will go through all the methods you create on this object (in the order you created them) and run them one at a time. some method names have priority in this generator. the available priorities are in order:
- initializing - your initialization methods (config package.json etc)
- prompting - where you prompt users for options (where you'd call this.prompt())
- configuring - saving configurations and configure the project
- default
- writing - to parse and copy template-files to the outputfolder.
- conflicts - where conflicts are handled (used internally)
- install - where installation are run (npm, bower)
- end - called last, cleanup, say good bye , etc
i refer to the running context for more information about how methods are run and in which context.
2. initializing the generator
the first thing you have to do is initializing your generator with the package.json file. this file is a node.js module manifest. you can find this file in the root folder of the generator (the root folder is the place where .yo-rc.json is located). the package.json file must contain the following:
{
"name": "generator-myapp",
"version": "0.0.0",
"description": "scaffold out a front-end web app",
"license": "bsd",
"repository": "petereijgermans11/generator-myapp",
"author": {
"name": "",
"email": "",
"url": "https://github.com/petereijgermans11"
},
"main": "app/index.js",
"engines": {
"node": ">=0.10.0",
"npm": ">=1.3"
},
"scripts": {
"test": "mocha --reporter spec"
},
"files": [
"app"
],
"keywords": [
"yeoman-generator",
"web",
"app",
"front-end",
"h5bp",
"modernizr",
"jquery",
"angular",
"gulp"
],
"dependencies": {
"chalk": "^1.0.0",
"wiredep": "^2.2.2",
"yeoman-generator": "^0.18.5",
"yeoman-assert": "^2.0.0",
"yosay": "^1.0.0"
},
"peerdependencies": {
"yo": ">=1.0.0",
"generator-mocha": ">=0.1.0",
"gulp": ">=3.5.0"
},
"devdependencies": {
"mocha": "*"
}
}
how this package.json file is composed i refer to package.json . i use the following dependencies:
- chalk : to log a coloured message with yeoman
- wiredep : for injecting bower components to your html/scss files.
- yeoman-generator see yeoman
- yeoman-assert : assert utility from yeoman
- yosay : tell yeoman what to say in the console
i configured the following:
- yo : cli tool for running yeoman generators
- generator- mocha : a generator for the mocha test-framework
- gulp : a front-end build tool
and finally i defined the devdependency on the mocha-test test-framework.
to initialize the package.json file, we will add the initializing- method to the index.js:
'use strict';
var fs = require('fs');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');
var wiredep = require('wiredep');
var myappgenerator = yeoman.generators.base.extend({
initializing: function () {
this.pkg = require('../../package.json');
}
});
module.exports = myappgenerator;
3. getting user input
you can add questions to your generator so that you can receive input from the user. you can use this input while generating the final project. we are going to have the following questions in our generator:
- would you like angularjs or jquery ?
- what more front-end frameworks would you like? (sass, bootstrap or modernizr).
to accomplish this, we will add the prompting function to the index.js , that will prompt the user for this info and then store the results on our generator object (myappgenerator) itself:
'use strict';
var fs = require('fs');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');
var wiredep = require('wiredep');
var myappgenerator = yeoman.generators.base.extend({
initializing: function () {
this.pkg = require('../../package.json');
},
prompting: function () {
var done = this.async();
if (!this.options['skip-welcome-message']) {
this.log(yosay('out of the box i include html5 boilerplate, angularjs, jquery and a gulpfile.js to build your app.'));
}
var prompts = [{
type: 'checkbox',
name: 'mainframeworks',
message:'would you like angularjs or jquery ?',
choices: [{
name: 'angular',
value: 'includeangular',
checked: true
}, {
name: 'jquery',
value: 'includejquery',
checked: true
}]
},
{
type: 'checkbox',
name: 'features',
message:'what more front-end frameworks would you like ?',
choices: [{
name: 'sass',
value: 'includesass',
checked: true
}, {
name: 'bootstrap',
value: 'includebootstrap',
checked: true
}, {
name: 'modernizr',
value: 'includemodernizr',
checked: true
}]
}
];
this.prompt(prompts, function (answers) {
var features = answers.features;
var mainframeworks = answers.mainframeworks;
var hasfeature = function (feat) {
return features.indexof(feat) !== -1;
};
var hasmainframeworks = function (mainframework) {
return mainframeworks.indexof(mainframework) !== -1;
};
// manually deal with the response, get back and store the results.
this.includesass = hasfeature('includesass');
this.includebootstrap = hasfeature('includebootstrap');
this.includemodernizr = hasfeature('includemodernizr');
this.includeangular = hasmainframeworks('includeangular');
this.includejquery = hasmainframeworks('includejquery');
done();
}.bind(this));
}
});
module.exports = myappgenerator;
this function sets a done variable from the object's async method. yeoman tries to run your methods in the order that they are defined, but if you run any async code, the function will exit before the actual work gets done and yeoman will start the next function early. to solve this you have to call the async method which returns a callback. when the callback gets executed, yeoman will go on to the next function.
next, we defined a list of prompts, each prompt has a type, a name and a message. if no type was specified, it will default to ‘input' which is a text entry.
with the array of questions ready, we can pass it to the prompt method along with a callback function. the first parameter of the callback function is the list of answers received back from the user. we then attach those answers onto our generator object (referenced by ‘this’) and call the done method to go on to the next function in the generator object.
4. options and arguments
the user can pass options to generator (index.js) from the command line:
yo myapp --skip-install-message
in our case we like to have options for the following:
--skip-welcome-message
skips yeoman's greeting before displaying options.
--skip-install-message
skips the message displayed after scaffolding has finished and before the dependencies are being installed.
--skip-install
skips the automatic execution of bower and npm after scaffolding has finished.
--test-framework=<framework>
defaults to mocha . can be switched for another supported testing framework like jasmine .
in our generator the arguments and options should be defined in the constructor method:
var myappgenerator = yeoman.generators.base.extend({
constructor: function () {
yeoman.generators.base.apply(this, arguments);
this.option('test-framework', {
desc: 'test framework to be invoked',
type: string,
defaults: 'mocha'
});
this.option('skip-welcome-message', {
desc: 'skips the welcome message',
type: boolean
});
this.option('skip-install', {
desc: 'skips the installation of dependencies',
type: boolean
});
this.option('skip-install-message', {
desc: 'skips the message after the installation of dependencies',
type: boolean
});
},
5. adding custom templates
all i have to do in this section is creating all the template files in the generators/<sub-generator>/ templates folder. i want to create the following template files:
- gulpfile.js
- _package.json
- bowerrc
- bower.json
- gitignore
- gitattributes
- jshintrc
- editorconfig
- robots.txt
- index.html
- main.css
- main.scss
- main.js
gulpfile.js
i want to use gulp as build system . for gulp i need to define a gulpfile.js. i use ejs-styled placeholders in this template file, which will be filled in by our yeoman-generator at runtime.
create the /generator-myapp/generators/app/templates/ gulpfile.js containing:
/*global -$ */
'use strict';
// generated on <%= (new date).toisostring().split('t')[0] %> using <%= pkg.name %> <%= pkg.version %>
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var browsersync = require('browser-sync');
var reload = browsersync.reload;
gulp.task('styles', function () {<% if (includesass) { %>
gulp.src('app/styles/*.scss')
.pipe($.sourcemaps.init())
.pipe($.sass({
outputstyle: 'expanded',
precision: 10,
includepaths: ['.']
}).on('error', $.sass.logerror))<% } else { %>
return gulp.src('app/styles/*.css')
.pipe($.sourcemaps.init())<% } %>
.pipe($.postcss([
require('autoprefixer-core')({browsers: ['last 1 version']})
]))
.pipe($.sourcemaps.write())
.pipe(gulp.dest('.tmp/styles'))
.pipe(reload({stream: true}));
});
function jshint(files) {
return function () {
return gulp.src(files)
.pipe(reload({stream: true, once: true}))
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.if(!browsersync.active, $.jshint.reporter('fail')));
};
}
gulp.task('jshint', jshint('app/scripts/**/*.js'));
gulp.task('jshint:test', jshint('test/spec/**/*.js'));
gulp.task('html', ['styles'], function () {
var assets = $.useref.assets({searchpath: ['.tmp', 'app', '.']});
return gulp.src('app/*.html')
.pipe(assets)
.pipe($.if('*.js', $.uglify()))
.pipe($.if('*.css', $.csso()))
.pipe(assets.restore())
.pipe($.useref())
.pipe($.if('*.html', $.minifyhtml({conditionals: true, loose: true})))
.pipe(gulp.dest('dist'));
});
gulp.task('images', function () {
return gulp.src('app/images/**/*')
.pipe($.if($.if.isfile, $.cache($.imagemin({
progressive: true,
interlaced: true,
// don't remove ids from svgs, they are often used
// as hooks for embedding and styling
svgoplugins: [{cleanupids: false}]
}))
.on('error', function(err){ console.log(err); this.end; })))
.pipe(gulp.dest('dist/images'));
});
gulp.task('fonts', function () {
return gulp.src(require('main-bower-files')({
filter: '**/*.{eot,svg,ttf,woff,woff2}'
}).concat('app/fonts/**/*'))
.pipe(gulp.dest('.tmp/fonts'))
.pipe(gulp.dest('dist/fonts'));
});
gulp.task('extras', function () {
return gulp.src([
'app/*.*',
'!app/*.html'
], {
dot: true
}).pipe(gulp.dest('dist'));
});
gulp.task('clean', require('del').bind(null, ['.tmp', 'dist']));
gulp.task('serve', ['styles', 'fonts'], function () {
browsersync({
notify: false,
port: 9000,
server: {
basedir: ['.tmp', 'app'],
routes: {
'/bower_components': 'bower_components'
}
}
});
// watch for changes
gulp.watch([
'app/*.html',
'app/scripts/**/*.js',
'app/images/**/*',
'.tmp/fonts/**/*'
]).on('change', reload);
gulp.watch('app/styles/**/*.<%= includesass ? 'scss' : 'css' %>', ['styles']);
gulp.watch('app/fonts/**/*', ['fonts']);
gulp.watch('bower.json', ['wiredep', 'fonts']);
});
gulp.task('serve:dist', function () {
browsersync({
notify: false,
port: 9000,
server: {
basedir: ['dist']
}
});
});
gulp.task('serve:test', function () {
browsersync({
notify: false,
open: false,
port: 9000,
ui: false,
server: {
basedir: 'test'
}
});
gulp.watch([
'test/spec/**/*.js',
]).on('change', reload);
gulp.watch('test/spec/**/*.js', ['jshint:test']);
});
// inject bower components
gulp.task('wiredep', function () {
var wiredep = require('wiredep').stream;
<% if (includesass) { %>
gulp.src('app/styles/*.scss')
.pipe(wiredep({
ignorepath: /^(\.\.\/)+/
}))
.pipe(gulp.dest('app/styles'));
<% } %>
gulp.src('app/*.html')
.pipe(wiredep({<% if (includesass && includebootstrap) { %>
exclude: ['bootstrap-sass'],<% } %>
ignorepath: /^(\.\.\/)*\.\./
}))
.pipe(gulp.dest('app'));
});
gulp.task('build', ['jshint', 'html', 'images', 'fonts', 'extras'], function () {
return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});
gulp.task('default', ['clean'], function () {
gulp.start('build');
});
the gulpfile supports the following:
- css autoprefixing: a postprocessor for making css appropriate for all browsers.
- compile sass/.scss files with libsass
- minifies all your .css and .js files and html-files
- map compiled css to source stylesheets with source maps
- built-in preview server with browsersync . bowersync watch all files and update connected browsers if a change occurs in your files.
- lint your scripts via jshint
- image optimization
- wire-up dependencies installed with bower
- inject bower components to your html/scss files via the wiredep task.
- use the .tmp directory mostly for compiling assets like scss files. it has precedence over app, so if you had an app/index.html template compiling to .tmp/index.html, your application would point to .tmp/index.html, which is what we want.
for more information on what this generator can do for you, take a look at the ‘ gulp-plugins ’ used in our package.json in the next section. as you might have noticed, gulp plugins (the ones that begin with gulp-) don't have to be required. they are automatically picked up by gulp-load-plugin and available through the $ variable.
_package.json
create the /generator-myapp/generators/app/templates/ _package.json containing:
{
"private": true,
"engines": {
"node": ">=0.12.0"
},
"devdependencies": {
"autoprefixer-core": "^5.1.8",
"browser-sync": "^2.2.1",
"del": "^1.1.1",
"gulp": "^3.8.11",
"gulp-cache": "^0.2.8",
"gulp-csso": "^1.0.0",
"gulp-if": "^1.2.5",
"gulp-imagemin": "^2.2.1",
"gulp-jshint": "^1.9.2",
"gulp-load-plugins": "^0.8.1",
"gulp-minify-html": "^1.0.0",
"gulp-postcss": "^5.0.0",<% if (includesass) { %>
"gulp-sass": "^2.0.0",<% } %>
"gulp-size": "^1.2.1",
"gulp-sourcemaps": "^1.5.0",
"gulp-uglify": "^1.1.0",
"gulp-useref": "^1.1.1",
"jshint-stylish": "^1.0.1",
"main-bower-files": "^2.5.0",
"opn": "^1.0.1",
"wiredep": "^2.2.2"
}
}
bowerrc
i use bower as the the web package manager. the default place bower will install its dependencies is ./bower-components.
create the /generator-myapp/generators/app/templates/ bowerrc containing:
{
"directory": "bower_components"
}
bower.json
packages are defined by a manifest file bower.json.
create the /generator-myapp/generators/app/templates/ bower.json containing:
{
"name": "package",
"version": "0.0.0",
"dependencies": {}
}
gitignore
create the /generator-myapp/generators/app/templates /gitignore containing:
node_modules
dist
.tmp
.sass-cache
bower_components
test/bower_components
gitattributes
create the /generator-myapp/generators/app/templates/ gitattributes containing:
* text=auto
jshintrc
i use jshint to enable warnings in the javascript.
create the /generator-myapp/generators/app/templates /jshintrc containing:
{
"browser": true,
"node": true,
"esnext": true,
"bitwise": true,
"camelcase": true,
"curly": true,
"eqeqeq": true,
"immed": true,
"indent": 2,
"latedef": true,
"newcap": true,
"noarg": true,
"quotmark": "single",
"undef": true,
"unused": true,
"strict": true,
"angular": true
}
index.html
i want to define a single page for my scaffolding. i use ejs-styled placeholders (<% … %>) in this template file, which will be filled in by our yeoman-generator at runtime. on the other hand i have inserted placeholders in the index.html for injecting bower dependencies using the wiredep -plugin. these placeholders have the following syntax:
<html>
<head>
<!-- bower:css -->
<!-- endbower -->
</head>
<body>
<!-- bower:js -->
<!-- endbower -->
</body>
</html>
create the /generator-myapp/generators/app/templates/ index.html containing:
<!doctype html>
<html<% if (includemodernizr) { %> class="no-js"<% } %> lang="">
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><%= appname %></title>
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<!-- place favicon.ico in the root directory -->
<!-- build:css styles/vendor.css -->
<!-- bower:css -->
<!-- endbower -->
<!-- endbuild -->
<!-- build:css styles/main.css -->
<link rel="stylesheet" href="styles/main.css">
<!-- endbuild -->
<% if (includemodernizr) { %>
<!-- build:js scripts/vendor/modernizr.js -->
<script src="/bower_components/modernizr/modernizr.js"></script>
<!-- endbuild --><% } %>
</head>
<body>
<!--[if lt ie 10]>
<p class="browserupgrade">you are using an <strong>outdated</strong> browser. please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<% if (includebootstrap) { %>
<div class="container">
<div class="header">
<ul class="nav nav-pills pull-right">
<li class="active"><a href="#">home</a></li>
<li><a href="#">about</a></li>
<li><a href="#">contact</a></li>
</ul>
<h3 class="text-muted"><%= appname %></h3>
</div>
<div class="jumbotron">
<h1>hello!</h1>
<p class="lead">gulp scaffolding app.</p>
<p><a class="btn btn-lg btn-success" href="#">button!</a></p>
</div>
<div class="row marketing">
<div class="col-lg-6">
<h4>html5 boilerplate</h4>
<p>html5 boilerplate is a professional front-end template for building fast, robust, and adaptable web apps or sites.</p>
<% if (includeangular) { %>
<h4>angularjs</h4>
<p>you have angujarjs</p>
<% } %>
<% if (includejquery) { %>
<h4>jquery</h4>
<p>you have jquery</p>
<% } %>
<% if (includesass) { %>
<h4>sass</h4>
<p>sass is the most mature, stable, and powerful professional grade css extension language in the world.</p>
<% } %>
<h4>bootstrap</h4>
<p>sleek, intuitive, and powerful mobile first front-end framework for faster and easier web development.</p><% if (includemodernizr) { %>
<h4>modernizr</h4>
<p>modernizr is an open-source javascript library that helps you build the next generation of html5 and css3-powered websites.</p>
<% } %>
</div>
</div>
<div class="footer">
<p>footer placeholder</p>
</div>
</div>
<% } else { %>
<div class="hero-unit">
<h1>hello!</h1>
<p>you now have</p>
<ul>
<% if (includeangular) { %>
<li>angujarjs</li>
<% } %>
<% if (includejquery) { %>
<li>jquery</li>
<% } %>
<li>html5 boilerplate</li><% if (includesass) { %>
<li>sass</li><% } %><% if (includemodernizr) { %>
<li>modernizr</li><% } %>
</ul>
</div>
<% } %>
<!-- google analytics: change ua-xxxxx-x to be your site's id. -->
<script>
(function(b,o,i,l,e,r){b.googleanalyticsobject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new date;
e=o.createelement(i);r=o.getelementsbytagname(i)[0];
e.src='https://www.google-analytics.com/analytics.js';
r.parentnode.insertbefore(e,r)}(window,document,'script','ga'));
ga('create','ua-xxxxx-x');ga('send','pageview');
</script>
<!-- build:js scripts/vendor.js -->
<!-- bower:js -->
<!-- endbower -->
<!-- endbuild -->
</body>
</html>
main.css
i need to define default styling.
create the /generator-myapp/generators/app/templates/ main.css containing:
<% if (includebootstrap) { %>.browserupgrade {
margin: 0.2em 0;
background: #ccc;
color: #000;
padding: 0.2em 0;
}
/* space out content a bit */
body {
padding-top: 20px;
padding-bottom: 20px;
}
/* everything but the jumbotron gets side spacing for mobile first views */
.header,
.marketing,
.footer {
padding-left: 15px;
padding-right: 15px;
}
/* custom page header */
.header {
border-bottom: 1px solid #e5e5e5;
}
/* make the masthead heading the same height as the navigation */
.header h3 {
margin-top: 0;
margin-bottom: 0;
line-height: 40px;
padding-bottom: 19px;
}
/* custom page footer */
.footer {
padding-top: 19px;
color: #777;
border-top: 1px solid #e5e5e5;
}
.container-narrow > hr {
margin: 30px 0;
}
/* main marketing message and sign up button */
.jumbotron {
text-align: center;
border-bottom: 1px solid #e5e5e5;
}
.jumbotron .btn {
font-size: 21px;
padding: 14px 24px;
}
/* supporting marketing content */
.marketing {
margin: 40px 0;
}
.marketing p + h4 {
margin-top: 28px;
}
/* responsive: portrait tablets and up */
@media screen and (min-width: 768px) {
.container {
max-width: 730px;
}
/* remove the padding we set earlier */
.header,
.marketing,
.footer {
padding-left: 0;
padding-right: 0;
}
/* space out the masthead */
.header {
margin-bottom: 30px;
}
/* remove the bottom border on the jumbotron for visual effect */
.jumbotron {
border-bottom: 0;
}
}<% } else { %>body {
background: #fafafa;
font-family: "helvetica neue", helvetica, arial, sans-serif;
color: #333;
}
.hero-unit {
margin: 50px auto 0 auto;
width: 300px;
font-size: 18px;
font-weight: 200;
line-height: 30px;
background-color: #eee;
border-radius: 6px;
padding: 60px;
}
.hero-unit h1 {
font-size: 60px;
line-height: 1;
letter-spacing: -1px;
}
.browserupgrade {
margin: 0.2em 0;
background: #ccc;
color: #000;
padding: 0.2em 0;
}<% } %>
main.scss
when i want to support sass, i need a file containing scss for my styling.
create the /generator-myapp/generators/app/templates/ main.scss containing:
<% if (includebootstrap) { %>$icon-font-path: '../fonts/';
// bower:scss
// endbower
.browserupgrade {
margin: 0.2em 0;
background: #ccc;
color: #000;
padding: 0.2em 0;
}
/* space out content a bit */
body {
padding-top: 20px;
padding-bottom: 20px;
}
/* everything but the jumbotron gets side spacing for mobile first views */
.header,
.marketing,
.footer {
padding-left: 15px;
padding-right: 15px;
}
/* custom page header */
.header {
border-bottom: 1px solid #e5e5e5;
/* make the masthead heading the same height as the navigation */
h3 {
margin-top: 0;
margin-bottom: 0;
line-height: 40px;
padding-bottom: 19px;
}
}
/* custom page footer */
.footer {
padding-top: 19px;
color: #777;
border-top: 1px solid #e5e5e5;
}
.container-narrow > hr {
margin: 30px 0;
}
/* main marketing message and sign up button */
.jumbotron {
text-align: center;
border-bottom: 1px solid #e5e5e5;
.btn {
font-size: 21px;
padding: 14px 24px;
}
}
/* supporting marketing content */
.marketing {
margin: 40px 0;
p + h4 {
margin-top: 28px;
}
}
/* responsive: portrait tablets and up */
@media screen and (min-width: 768px) {
.container {
max-width: 730px;
}
/* remove the padding we set earlier */
.header,
.marketing,
.footer {
padding-left: 0;
padding-right: 0;
}
/* space out the masthead */
.header {
margin-bottom: 30px;
}
/* remove the bottom border on the jumbotron for visual effect */
.jumbotron {
border-bottom: 0;
}
}<% } else { %>// bower:scss
// endbower
body {
background: #fafafa;
font-family: 'helvetica neue', helvetica, arial, sans-serif;
color: #333;
}
.hero-unit {
margin: 50px auto 0 auto;
width: 300px;
font-size: 18px;
font-weight: 200;
line-height: 30px;
background-color: #eee;
border-radius: 6px;
padding: 60px;
h1 {
font-size: 60px;
line-height: 1;
letter-spacing: -1px;
}
}
.browserupgrade {
margin: 0.2em 0;
background: #ccc;
color: #000;
padding: 0.2em 0;
}<% } %>
main.js
create the /generator-myapp/generators/app/templates/ main.js containing:
/* jshint devel:true */
console.log('hello!');
robot.txt
create an empty /generator-myapp/generators/app/templates/ robot.txt
6. write the generator specific files
in this section i finally parse and copy the templates from ‘ /generator-myapp/generators/app/templates/ ’ to the outputfolder . the outputfolder is the folder where the user want to generate his scaffolding.
these actions are performed in the the ‘ writing method’ in the index.js file. the index.js should contain the following:
var myappgenerator = yeoman.generators.base.extend({
writing: {
gulpfile: function () {
this.template('gulpfile.js');
},
packagejson: function () {
this.template('_package.json', 'package.json');
},
git: function () {
this.fs.copy(
this.templatepath('gitignore'),
this.destinationpath('.gitignore')
);
this.fs.copy(
this.templatepath('gitattributes'),
this.destinationpath('.gitattributes')
);
},
bower: function () {
var bower = {
name: this._.slugify(this.appname),
private: true,
dependencies: {}
};
if (this.includebootstrap) {
var bs = 'bootstrap' + (this.includesass ? '-sass' : '');
bower.dependencies[bs] = '~3.3.1';
}
if (this.includemodernizr) {
bower.dependencies.modernizr = '~2.8.1';
}
if (this.includeangular) {
bower.dependencies.angular = '~1.3.15';
}
if (this.includejquery) {
bower.dependencies.jquery = '~2.1.1';
}
this.fs.copy(
this.templatepath('bowerrc'),
this.destinationpath('.bowerrc')
);
this.write('bower.json', json.stringify(bower, null, 2));
},
jshint: function () {
this.fs.copy(
this.templatepath('jshintrc'),
this.destinationpath('.jshintrc')
);
},
h5bp: function () {
this.fs.copy(
this.templatepath('favicon.ico'),
this.destinationpath('app/favicon.ico')
);
this.fs.copy(
this.templatepath('apple-touch-icon.png'),
this.destinationpath('app/apple-touch-icon.png')
);
this.fs.copy(
this.templatepath('robots.txt'),
this.destinationpath('app/robots.txt')
);
},
mainstylesheet: function () {
var css = 'main';
if (this.includesass) {
css += '.scss';
} else {
css += '.css';
}
this.copy(css, 'app/styles/' + css);
},
writeindex: function () {
this.indexfile = this.src.read('index.html');
this.indexfile = this.engine(this.indexfile, this);
// wire bootstrap plugins
if (this.includebootstrap) {
var bs = '/bower_components/';
if (this.includesass) {
bs += 'bootstrap-sass/assets/javascripts/bootstrap/';
} else {
bs += 'bootstrap/js/';
}
this.indexfile = this.appendscripts(this.indexfile, 'scripts/plugins.js', [
bs + 'affix.js',
bs + 'alert.js',
bs + 'dropdown.js',
bs + 'tooltip.js',
bs + 'modal.js',
bs + 'transition.js',
bs + 'button.js',
bs + 'popover.js',
bs + 'carousel.js',
bs + 'scrollspy.js',
bs + 'collapse.js',
bs + 'tab.js'
]);
}
this.indexfile = this.appendfiles({
html: this.indexfile,
filetype: 'js',
optimizedpath: 'scripts/main.js',
sourcefilelist: ['scripts/main.js']
});
this.write('app/index.html', this.indexfile);
},
app: function () {
this.copy('main.js', 'app/scripts/main.js');
}
},
this ‘writing’ method supports the following:
- gulpfile: parse the gulpfile.js and copy it to the outputfolder
- packagejson : copy package.json to the outputfolder
- bower: add dependencies to the bower.json and copy it to the outputfolder
- mainstylesheet : copy the desired stylesheet
- writeindex: wire the bootstrapplugins and the main.js at the end of the index.html.
- app: copy the main.js file
7. install npm and bower
once you've run your generators, you'll often want to run npm and bower to install any additional dependencies your generators require. in our generator ( index.js ) the installation of the dependencies should be defined in the install method:
install: function () {
var howtoinstall =
'\nafter running ' +
chalk.yellow.bold('npm install & bower install') +
', inject your' +
'\nfront end dependencies by running ' +
chalk.yellow.bold('gulp wiredep') +
'.';
if (this.options['skip-install']) {
this.log(howtoinstall);
return;
}
this.installdependencies({
skipmessage: this.options['skip-install-message'],
skipinstall: this.options['skip-install']
});
this.on('end', function () {
var bowerjson = this.dest.readjson('bower.json');
// wire bower packages to .html
wiredep({
bowerjson: bowerjson,
directory: 'bower_components',
exclude: ['bootstrap-sass', 'bootstrap.js'],
ignorepath: /^(\.\.\/)*\.\./,
src: 'app/index.html'
});
if (this.includesass) {
// wire bower packages to .scss
wiredep({
bowerjson: bowerjson,
directory: 'bower_components',
ignorepath: /^(\.\.\/)+/,
src: 'app/styles/*.scss'
});
}
// ideally we should use composewith, but we're invoking it here
// because generator-mocha is changing the working directory
// https://github.com/yeoman/generator-mocha/issues/28
this.invoke(this.options['test-framework'], {
options: {
'skip-message': this.options['skip-install-message'],
'skip-install': this.options['skip-install']
}
});
}.bind(this));
}
this install method supports the following:
- call installdependencies() to run both npm and bower
- after the installation, i use the ‘end-queue’, to wire the bower packages in the index.html en main.scss.
- and last but not least i install the desired test-framework. the default is the mocha-testframework.
8. scaffold your app
after all these work, run this command in your generators root directory (the root folder is where you can find the:.yo-rc.json).
npm link
make a new folder on your filesystem and scaffold your very own web app:
mkdir testmyapp
cd testmyapp
yo myapp

a new scaffolding will be generated in the outputfolder: testmyapp and the dependencies are installed.
to start developing, run:
npm install -g gulp
gulp serve
this will fire up a local web server, open http://localhost:9000 in your default browse. the browser reloaded automatically when you changes one of your html/js//css-files.
to make a production-ready build of the app, run:
gulp
9. unittest
to test your app, run:
gulp serve:test
conclusion
in this article, we covered a lot of the common features but there are still more features to check out. there is a bit of boilerplate required when building a generator, but you have to build it once and then you're able to use it throughout all your applications.
yeoman is a great tool designed for front-end web developers. it helps you kick-start new projects and is a very powerful addition to every front-end developer’s arsenal.
this is all about building your own yeoman generator.
cheerz,
peter eijgermans
i committed the whole project to github or here .
related topics
· create-and-publish-a-yeoman-generator
Opinions expressed by DZone contributors are their own.
Comments