美文网首页
使用yeoman generator创建脚手架

使用yeoman generator创建脚手架

作者: RebeccaYan | 来源:发表于2017-07-04 11:37 被阅读128次

    开发时,经常会需要拷贝原有的目录结构和代码,如果有脚手架帮助做这些事,可以省去不少工作量。yeoman的generator就可以帮助我们构建这样的脚手架。

    前期准备

    首先,确保本地开发环境安装了NodeNPM。需要注意Node的版本,要求在4.0以上,NPM的版本也需要和Node版本相匹配。另外,高版本的Node会支持更多的ES6特性,方便使用新语法来书写代码。

    接着,全局安装yeoman

    npm install yeoman -g
    

    yeoman支持为自己的脚手架建立一个generator,通过运行generator来生成脚手架。

    建立项目

    首先,创建项目文件夹,文件夹名格式为generator-name,其中name是需要创建的generator的名字。比如我需要创建的是一个webpack用法示例的项目脚手架,文件夹取名为generator-webpack-example

    然后,初始化项目,并根据提示输入项目信息。

    npm init
    

    接着,创建项目所需的结构。使用yeoman执行generator时(比如yo webpack-example),yeoman默认会去执行app目录下的入口文件,代码需要放在app中。并且命令会从app中的templates目录读取模板。详细配置参考官方文章WRITING YOUR OWN YEOMAN GENERATOR

    最后项目的结构如下。

    - app
     |- templates
     |- index.js
     |- prompts.js
    - package.json
    - README.md
    

    模板结构

    templates目录用来存放产出文件的模板。脚手架的实现使用了lodash,所以模板直接使用lodash提供的模板语法。templates目录中的结构如下。

    - templates
     |- index_tmpl.html
     |- index_tmpl.js
     |- package_tmpl.json
     |- README_tmpl.md
     |- webpack_tmpl.config.js
    

    代码实现

    index.js是主文件,用来实现脚手架的具体操作。其中class中使用的各方法是yeoman的generator提供的函数钩子,针对功能填充到对应的钩子函数中即可。可用的钩子方法可参考GENERATOR RUNTIME CONTEXT

    首先,安装文件依赖的模块。

    npm install yeoman-generator chalk yosay lodash deep-extend mkdirp -S
    

    然后,使用Generator的API实现脚手架。

    'use strict';
    const Generator = require('yeoman-generator');
    const chalk = require('chalk');
    const yosay = require('yosay');
    const path = require('path');
    const _ = require('lodash');
    const extend = require('deep-extend');
    const mkdirp = require('mkdirp');
    
    const prompts = require('./prompts');
    
    module.exports = class extends Generator {
    
      initializing() {
    
        this.props = {};
      }
    
      prompting() {
    
        // 打招呼
        this.log(yosay(
          'Welcome to the ' + chalk.red('generator-webpack-example') + ' generator!'
        ));
    
        return this.prompt(prompts).then(props => {
          this.props = props;
        })
      }
    
      writing() {
    
        if (path.basename(this.destinationPath()) !== this.props.projectName) {
          this.log(
            'Your generator must be inside a folder named ' + this.props.projectName + '\n' +
            'I\'ll automatically create this folder.'
          );
          mkdirp(this.props.projectName);
          this.destinationRoot(this.destinationPath(this.props.projectName));
        }
    
        // 写README.md
        const readmeTpl = _.template(this.fs.read(this.templatePath('README_tmpl.md')));
        this.fs.write(this.destinationPath('README.md'), readmeTpl({
          projectTitle: this.props.projectTitle,
          projectDesc: this.props.projectDesc
        }));
    
        // 写package.json
        const pkg = this.fs.readJSON(this.templatePath('package_tmpl.json'), {});
        extend(pkg, {
          devDependencies: {
            "webpack": "^3.0.0"
          }
        });
        pkg.keywords = pkg.keywords || [];
        pkg.keywords.push('generator-webpack-example');
    
        pkg.name = this.props.projectName;
        pkg.description = this.props.projectDesc;
        pkg.main = this.props.projectMain;
        pkg.author = this.props.projectAuthor;
        pkg.license = this.props.projectLicense;
    
        this.fs.writeJSON(this.destinationPath('package.json'), pkg);
    
        // 创建dist目录
        mkdirp('dist');
    
        // 写index.html
        const indexHtmlTpl = _.template(this.fs.read(this.templatePath('index_tmpl.html')));
        this.fs.write(this.destinationPath('dist/index.html'), indexHtmlTpl({
          projectName: this.props.projectName
        }));
    
        // 创建src目录
        mkdirp('src');
    
        // 写webpack.config.js
        this.fs.copy(
          this.templatePath('webpack_tmpl.config.js'),
          this.destinationPath('webpack.config.js')
        );
    
        // 写index.js
        this.fs.copy(
          this.templatePath('index_tmpl.js'),
          this.destinationPath('src/index.js')
        );
      }
    };
    

    prompts.js用于存放输入信息指引的配置。

    module.exports = [
      {
        type: 'input',
        name: 'projectName',
        message: 'Please input project name (webpack-example):',
        default: 'webpack-example'
      },
      {
        type: 'input',
        name: 'projectTitle',
        message: 'Please input project title (webpack示例):',
        default: 'webpack示例'
      },
      {
        type: 'input',
        name: 'projectDesc',
        message: 'Please input project description:'
      },
      {
        type: 'input',
        name: 'projectMain',
        message: 'Main file (src/index.js):',
        default: 'src/index.js'
      },
      {
        type: 'input',
        name: 'projectAuthor',
        message: 'Author (yanyinhong):',
        default: 'yanyinhong'
      },
      {
        type: 'list',
        name: 'projectLicense',
        message: 'Please choose license:',
        choices: ['MIT', 'ISC', 'Apache-2.0', 'AGPL-3.0']
      }
    ]
    

    运行

    项目还没有通过NPM发布,可以先将项目链接到全局Node环境中。

    npm link
    

    然后,尝试执行命令yo generator-name。比如:

    yo webpack-example
    

    根据提示步骤进行项目的构建:

    ? Please input project name (webpack-example): webpack-example
    ? Please input project title (webpack示例): webpack示例
    ? Please input project description:
    ? Main file (src/index.js): src/index.js
    ? Author (yanyinhong): yanyinhong
    ? Please choose license: MIT
    Your generator must be inside a folder named webpack-example
    I'll automatically create this folder.
       create README.md
       create package.json
       create dist\index.html
       create webpack.config.js
       create src\index.js
    

    一个项目构建完成了!

    相关文章

      网友评论

          本文标题:使用yeoman generator创建脚手架

          本文链接:https://www.haomeiwen.com/subject/cwwthxtx.html