前端脚手架搭建(三)插件编写 jfet-doc

427 阅读1分钟

jfet-doc

gitbook

package.json:

  "directories": {
    "doc": "doc"
  },

node命令包开发

根据不同命令进行对应处理

// handler
plugin.handler = (configuration, argv) => {
  // 得到配置
  const cfg = Object.assign({}, defaultOptions, getConfiguration(configuration, argv));
  let stream = null;

  co(function* () {
    const zipName = `${Date.now()}.zip`;
    const zipFullName = path.join(zipPath, zipName);

    try {
      // gitbook serve
      if (argv.serve) {
        stream = execa(gitbookBin, ['serve']).stdout;
        yield getStream(stream);
        return false;
      }

      // gitbook init
      if (argv.init) {
        stream = execa(gitbookBin, ['init']).stdout;
        yield getStream(stream);
        return false;
      }

      // gitbook install
      if (argv.install) {
        stream = execa(gitbookBin, ['install']).stdout;
        yield getStream(stream);
        return false;
      }

      // 不是build和publish
      if (!argv.build && !argv.publish) {
        console.log(chalk.green(`${pkg.name}${pkg.description}`));
        return false;
      }

      if (!normalizeFields(cfg)) {
        return false;
      }

      // gitbook build
      if (argv.build) {
        stream = execa(gitbookBin, ['build']).stdout;
        stream.pipe(process.stdout);
        yield getStream(stream);
      }

      const form = new FormStream();
      let result = null;

      // 写入docs_server.json文件
      fse.writeFileSync(path.join(cfg.fileDir, 'docs_server.json'), JSON.stringify({
        name: cfg.name || '',
        title: cfg.title || '',
        desc: cfg.desc || ''
      }, null, 2));

      // 新建zip目录
      fse.ensureDirSync(zipPath);
      // 创建压缩包
      yield util.createZip(zipFullName, zipName, cfg.fileDir);
      // 设置name,token,file
      form.field('name', cfg.name);
      form.field('token', cfg.token);
      form.file('file', zipFullName);
      // 提交
      result = yield urllib.request(cfg.uploadUrl, {
        method: 'POST',
        headers: form.headers(),
        stream: form,
        timeout: cfg.timeout || 5000
      });

      console.log(result.data.toString('utf-8'));
    } catch (e) {
      console.log(chalk.red(e));
    }

    // 移除压缩包
    yield fse.remove(zipFullName);
  });
};