Introduction to Yeoman Generator
Yeoman Generator is a powerful tool that helps developers kickstart new projects, ensuring best practices and consistent, high-quality code. This guide covers dozens of useful API explanations with code snippets to help you get the most out of Yeoman.
Getting Started
To create a new generator, first install Yeoman and create a new folder for your generator:
npm install -g yo mkdir my-generator cd my-generator yo generator
API Examples
Yeoman provides various APIs to customize the generator behavior:
1. The basic generator structure
const Generator = require('yeoman-generator'); module.exports = class extends Generator { writing() { this.fs.copyTpl( this.templatePath('index.html'), this.destinationPath('public/index.html'), { title: 'My App' } ); } };
2. Prompting users
const Generator = require('yeoman-generator'); module.exports = class extends Generator { prompting() { return this.prompt([{ type : 'input', name : 'name', message : 'Your project name', default : this.appname }]).then((answers) => { this.log('app name', answers.name); }); } };
3. Configuration storage
const Generator = require('yeoman-generator'); module.exports = class extends Generator { initializing() { this.config.set('foo', 'bar'); } writing() { this.log(this.config.get('foo')); } };
4. Composing generators
const Generator = require('yeoman-generator'); module.exports = class extends Generator { initializing() { this.composeWith(require.resolve('generator-node/generators/app'), { someOption: true }); } };
5. Handling file system operations
const Generator = require('yeoman-generator'); module.exports = class extends Generator { writing() { this.fs.write( this.destinationPath('file.txt'), 'Hello World!' ); } };
Example App
Here’s an example of a complete Yeoman generator for a simple app:
const Generator = require('yeoman-generator'); module.exports = class extends Generator { prompting() { return this.prompt([{ type : 'input', name : 'appname', message : 'Your project name', default : this.appname }]).then((answers) => { this.appname = answers.appname; }); } writing() { const tmpl = this.templatePath('**/*'); const dest = this.destinationPath(); const context = { appname: this.appname }; this.fs.copyTpl(tmpl, dest, context); } install() { this.installDependencies({ bower: false }); } };
This generator prompts for the project name and then scaffolds out a basic directory structure with the necessary files.
Conclusion
By using the Yeoman Generator, you can streamline your project setup process, maintain consistency, and utilize best practices across your projects. The provided API examples and a complete app example will help you get started quickly and effectively.
Keep exploring the Yeoman documentation to uncover more features and capabilities.
Hash: 888389f4a62c4f25de2a2f86d525b29a26c6d009d1f17051db98819fb04081d7