使用Yeoman定制前端脚手架

3,840 阅读3分钟

首先附上Yeoman官网:yeoman.io/

我制作的前端脚手架:generator-jake-front

以及我在前端同学的分享会上的分享ppt:yeoman.key

如果想快速制作一个脚手架,并且不需要实现特别复杂的定制化,看完这篇文章足够,如果想要实现复杂的功能,需要去查看官方文档

环境

需要安装Nodejs

全局安装需要的工具

npm install -g yo
npm install -g generator-generator

初始化项目

执行下面命令,执行之前并不需要自己新建文件夹,yo generator会帮助我们建好文件夹

yo generator

项目名称自己设置,必须是以generator-开头,协议选择MIT,在设置了一系列问题之后

自动生成如下目录

generator-test
├── LICENSE
├── README.md
├── __tests__
│   └── app.js
├── generators
│   └── app
│       ├── index.js
│       └── templates
│           └── dummyfile.txt
└── package.json

配置

generators/app/templates/是默认存放文件的目录,把所有模版文件放在这个目录下

/generators/app/index.jsYeoman的配置文件,定义如何生成我们的脚手架

prompting

Promptsgenerator与用户交互的主要方式。prompt模块由 Inquirer.js提供,你可以参考它的API,在可用的提示选项列表。

prompt方法是异步的并且返回一个 promise。在你运行下一个任务前去完成它,你需要返回 promise。

module.exports = class extends Generator {
  prompting() {
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the awe-inspiring ' + chalk.red('generator-downloads') + ' generator!'
    ));

    const prompts = [{
      type: 'confirm',
      name: 'someAnswer',
      message: 'Would you like to enable this option?',
      default: true
    }];

    return this.prompt(prompts).then(props => {
      // To access props later use this.props.someAnswer;
      this.props = props;
    });
  }
};

做一些适当的修改,实现更通用的脚手架。可以查阅API

  • this.appname: 获取当前文件夹名称
  • this.user.git.name(): 获取全局git用户名
  • this.user.git.email(): 获取全局git邮箱
  • this.github.username(): 获取github用户名

定义对象中的type,管理交互方式。使用input实现控制台输入。

type: 'input',
name: 'author',
message: 'author',
default: this.user.git.name()

这样便实现了让用户输入作者名称,默认为git全局配置的用户名。然后在其他配置中使用this.props.author实现获取用户输入。

writing

Generatorsthis.fs暴露了所有的文件的方法,这是一个实例,mem-fs editor - 确保为所有可获得的方法选择模块文件

值得注意的是,通过this.fs暴露commit,你不应该在你的generator去调用它。Yeoman在运行循环的冲突阶段结束后,在内部调用它。

复制一个模板文件

例如:./templates/index.html的文件内容是:

<html>
  <head>
    <title><%= title %></title>
  </head>
</html>

然后,我们将使用copyTpl方法去复制作为模板的处理中的文件。copyTpl使用的是ejs 模板引擎。

module.exports = class extends Generator {
  writing() {
    this.fs.copy(
      this.templatePath('index.html'),
      this.destinationPath('index.html'),
      { title: 'Templating with Yeoman' }
    );
  }
};

一旦generator运行成功,index.html将会包含:

<html>
  <head>
    <title>Templating with Yeoman</title>
  </head>
</html>

json也同样适用上面的语法,配置package.json文件可以适应不同的项目。

install

install方法设置在文件copy完成之后执行的命令,例如

module.exports = class extends Generator {
install() {
this.installDependencies({
      bower: true,
      npm: true,
      yarn: false,
      callback: function () {
       this.log('Everything is ready!');
      }
    });
  }
};

测试

由于我们在本地开发,并不知道用起来怎么样,所以可以使用npm link命令,相当于在全局安装了此脚手架,然后在新文件夹中执行yo,选择脚手架,便可以测试

发布

generator-test/package.json中的name要在www.npmjs.com/没被创建过,才可以发布。

发布需要一个npm的账号,如果没有使用npm adduser创建;

如果已有账号,运行npm login登陆。

在项目根目录下,运行npm publish就可以发布了。如果更新后重新发布,注意修改根目录下的package.json文件中的版本号。

使用npm unpublish 包名命令可以撤销发布,只有在发包的24小时内才允许撤销发布的包。