84741998 2019-06-25
对大多数一个前端团队来说,Yeoman(简称yo)是一个非常值得学习的工具,它为前端项目提供了一种行之有效的方法,开发、分发、使用项目手脚架,提高项目启动速度,复用项目结构。
本文以generator-iview-admin 为例,简单说明手脚架,即generator的开发过程。
开发 Yeoman 模板,需预先安装yo:
npm i -g yo
yo 细心的为我们准备了手脚架项目的手脚架generator-generator:
npm i -g generator-generator
安装后,进入开发目录,运行:
yo generator
执行上述命令后,主要生成如下文件:
├── .yo-rc.json ├── package.json ├── generators │ ├── app │ ├── templates │ ├── dummyfile.txt │ ├── index.js
其中
.yo-rc.json 用于存储项目配置,一般不会用到,无需关注package.json npm 项目信息文件,主要关注 author、version 域即可generators 目录即项目模板代码generators/templates 用于存放项目模板文件generators/app/index.js 定义项目手脚架的代码每个generator都会继承yeoman-generator类,即上述的generators/app/index.js文件。该类有几个重要的生命周期节点:
initializing - 初始化方法,用于获取项目状态、配置等prompting - 调用inquire方法获取用户输入configuring - 保存配置,创建 .editorconfig 等文件writing - 执行文件写操作,即项目文件写入文件系统中install - 执行安装操作,需调用 this.installDependencies 方法end - 最后执行,可清楚临时文件等上述方法均支持返回 Promise 方式实现异步操作,仅当返回的Promise 实例 resolve 时才会执行下一步操作。
首先,我们需要在 prompting 中询问用户配置(完整实例在此处):
prompting() {
  // Have Yeoman greet the user.
  this.log(yosay('Welcome to the divine ' + chalk.red('generator-iview-admin') + ' generator!'));
  const prompts = [{
    type: 'input',
    name: 'name',
    message: 'Your project name',
    default: this.appname
  }, {
    type: 'confirm',
    name: 'lint',
    message: 'Use ESLint to lint your code?'
  }, {
    name: 'lintStyle',
    type: 'list',
    message: 'Pick an ESLint preset',
    when(answers) {
      return answers.lint;
    },
    choices: [{
      name: 'Airbnb (https://github.com/airbnb/javascript)',
      value: 'airbnb',
      short: 'Airbnb'
    }, {
      name: 'Standard (https://github.com/feross/standard)',
      value: 'standard',
      short: 'Standard'
    }]
  }];
  return this.prompt(prompts).then((props) => {
    // To access props later use this.props.someAnswer;
    this.props = props;
  });
}这里,将用户输入的结果配置到 this.props 对象中,方便后续访问。
yo 的核心,本质上是按需修改模板文件,一般包含三种方法:
以ejs方式为例,编写模板(完整实例在此处):
<% if(vueFile==='standalone'){ %>
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
<% } %>
...
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,<% if(vueFile==='runtime'){ %>
  render: h => h(App)<% } else if(vueFile==='standalone'){ %>
  template: '<App/>',
  components: { App }<% } %>
});获取配置后,可以正式开始将模板写入硬盘中(完整实例在此处):
writing() {
  this.initPackage();
  this.renderTplFile();
}
initPackage() {
  let pkg = this.fs.readJSON(this.templatePath('package.json'), {});
  const {
    props
  } = this;
  pkg = _.merge(pkg, {
    name: props.name,
    description: props.description
  });
  
  ... 
  
  this.fs.writeJSON(this.destinationPath('package.json'), pkg);
}
renderTplFile() {
  let target = [
    ...
    'src/components/Hello.vue',
  ];
  if (this.props.unitTest) {
    target = target.concat([
      ...
      'build/webpack.test.conf.js'
    ]);
  }
  ...
  _.forEach(target, (file) => {
    this.fs.copyTpl(
      this.templatePath(file),
      this.destinationPath(file),
      this.props
    );
  });
}yo 提供mem-fs-editor实例接口,包含一系列fs工具:
this.fs.read - 读取文件this.fs.readJSON - 以JSON方式读取文件this.fs.write - 写文件this.fs.writeJson - 以JSON 方式写文件this.fs.append - 将内容已追加方式写入文件this.fs.extendJSON - 扩展JSON文件内容this.fs.delete - 删除文件此外,还有一系列路劲及模板接口:
this.fs.copyTpl - 复制模板文件,并按参数解析模板内容,写入目标文件中this.templatePath - 返回模板文件路径,即上述 generator/app/templates 中的文件路径this.destinationPath - 返回目标文件路径,即执行 yo 生成模板文件的路径this.registerTransformStream - 生命钩子接口,用于转化文件内容,兼容gulp插件至此,我们已了解开发一个yo模板所需要的所有接口。
yo允许添加任意数量的子模板,只需执行:
yo generator:subgenerator [name]
以yo generator:subgenerator test 为例,生成如下文件:
├── generators │ ├── app │ ├── test │ ├── templates │ ├── dummyfile.txt │ ├── index.js
templates、 index.js 文件的作用与上述无异,可直接开发。
可以通过如下方式,将项目加入本地generator 库:
npm link
之后,就可以执行如下命令,生成手脚架:
yo [your template name]
模板开发完毕后,如需发布可执行如下命令:
npm publish
注意:
npm adduser 操作进行登录https://registry.npmjs.org/ 源,切记切换。