Yeoman自定义脚手架实战

自定义脚手架实战

开始之前

原因

  • 规范项目结构,方便维护和优化
  • 避免互相拷贝代码,导致bug扩散
  • 减少重复代码,降低门槛

目标
自动生成一个 react型组件项目,使用eslint、stylelint、.editorconfig、postcssrc、babelrc、rollup。

模板
按照自己需求,先定义一个模板,并上传到github

脚手架模板搭建过程

脚手架模板地址: bulletin

使用 Yeoman

1、安装脚手架工具


npm install -g yo

验证是否安装成功:yo --version

报错信息:yo command not found

执行下语句

npm install -y -g yo
echo export PATH="$HOME/npm/bin:$PATH" >> ~/.bashrc
npm config set prefix ~/npm
echo "export NODE_PATH=$NODE_PATH:/home/$USER/npm/lib/node_modules" >> ~/.bashrc && source ~/.bashrc
npm install -y -g yo

2、 安装yo成功后, 生成 generator

 
npm install -g generator-generator
yo generator

生成过程
生成目录

3、用户交互

prompting 中询问用户,设置默认值“default”, 通过name取用户的输入值

  prompting() {
   ....
    const prompts = [
      {
        type: "input",
        name: "name",
        message: "Your component name",
        default: this.appname
      },
      {
        type: "input",
        name: "description",
        message: "Your component description",
        default: this.appname
      }
    ];

    return this.prompt(prompts).then(props => {
      this.props = props;
    });
  }

  writing() {
    this.log("*****appname***", this.appname);
    this.log("*****name***", this.props.name);
    this.log("****description", this.props.description);
   }

3、下载模板

在 generators/app/index.js 编写代码

destinationPath()方法,该方法主要用于获取路径。不传参时返回当前命令行运行的目录;如果收到多个参数,则会进行路径的拼接。

const download = require("download-git-repo");

module.exports = class extends Generator {

// ...

  _downloadTemplate() {
    return new Promise((resolve, reject) => {
      const dirPath = this.destinationPath(this.dirName, '.tmp');
      download('qqxu/bulletin', dirPath, err => {
        if (err) {
          reject(err);
          return;
        }
        resolve();
      });
    });
  }


// ...
}

_downloadTemplate()方法带了一个下划线前缀。Yeoman 执行顺序中有个default阶段,该阶段包含了所有用户自定义的类方法。如果某些方法不希望被 Yeoman 的脚手架流程直接调用,则可以添加一个下划线前缀。这种命名的方法,会在default阶段被忽略。

4、拷贝模板中的文件

module.exports = class extends Generator {


 // 拷贝模板的文件
  _walk(filePath, templateRoot) {
    if (fs.statSync(filePath).isDirectory()) {
      fs.readdirSync(filePath).forEach(name => {
        this._walk(path.resolve(filePath, name), templateRoot);
      });
      return;
    }

    const relativePath = path.relative(templateRoot, filePath);
    const destination = this.destinationPath(this.dirName, relativePath);
    this.fs.copyTpl(filePath, destination, {
      dirName: this.dirName
    });
  }


// ...
}

5、writing阶段

module.exports = class extends Generator {
// ...

    writing() {
        const done = this.async();
        this._downloadTemplate()
            .then(() => {
                const templateRoot = this.destinationPath(this.dirName, '.tmp');
                this._walk(templateRoot, templateRoot);
                fs.removeSync(templateRoot);
                done();
            })
            .catch(err => {
                this.env.error(err);
            });
    }

// ...

}

6、利用用户交互数据更新package.json

  _initPackage() {
    let pkg = this.fs.readJSON(this.destinationPath("package.json"), {});
    const { props } = this;
    pkg = _.merge(pkg, {
      name: props.name,
      description: props.description,
      author: props.author,
      keywords: props.keywords,
    });
    this.fs.writeJSON(this.destinationPath("package.json"), pkg);
  }

测试

npm link 使用

利用npm link进行测试

在脚手架项目generator-component-lego目录下执行

npm link

在新文件夹中执行

yo component-qqxu

1、遇到的问题

问题一:The "path" argument must be of type string. Received undefined

使用this.log发现this.dirName为undefined,导致上述错误,所以:

this.destinationPath(this.dirName || "", relativePath);

问题二:fs is not defined

Node fs文件系统

安装fs模块并引入npm install -S fs

const fs = require("fs");

module.exports = class extends Generator {
...
}

问题三:fs.removeSync is not a function

更改上述fs模块为 fs-extra

npm install -S fs-extra

const fs = require("fs-extra");

源码地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269