已生成app模版为例,其他同理

./cli.js ( 脚本文件 )

  1. #!/usr/bin/env node
  2. // 命名行解析,获取参数
  3. const yParser = require('yargs-parser');
  4. const semver = require('semver');
  5. // 文件管理
  6. const { existsSync } = require('fs');
  7. // 路径管理
  8. const { join } = require('path');
  9. // 控制台内容颜色控制
  10. const chalk = require('chalk');
  11. const run = require('./lib/run');
  12. // print version and @local
  13. /**
  14. * process.argv: 返回一个数组,其中包含当启动 Node.js 进程时传入的命令行参数
  15. * 第一个元素是 process.execPath
  16. * 第二个元素将是正在执行的 JavaScript 文件的路径。
  17. * 其余元素将是任何其他命令行参数。
  18. * node cli.js umi-project
  19. * ["/usr/local/bin/node", "/Users/wangyangyang/Downloads/code/demo/create-umi…", "umi-project"]
  20. */
  21. const args = yParser(process.argv.slice(2));
  22. if (args.v || args.version) {
  23. console.log(require('./package').version);
  24. if (existsSync(join(__dirname, '.local'))) {
  25. console.log(chalk.cyan('@local'));
  26. }
  27. process.exit(0);
  28. }
  29. /**
  30. * semver: 对npm包的版本管理,比较, 规范等等解析
  31. * https://cnodejs.org/topic/570f8331510629637266685a
  32. */
  33. if (!semver.satisfies(process.version, '>= 8.0.0')) {
  34. console.error(chalk.red('✘ The generator will only work with Node v8.0.0 and up!'));
  35. process.exit(1);
  36. }
  37. // 获取传入的项目名称
  38. const name = args._[0] || '';
  39. // 根据run文件得知,type设置项目的样板
  40. /**
  41. * 目前umi包含5种代码样板
  42. * ant-design-pro - Create project with a layout-only ant-design-pro boilerplate, use together with umi block.
  43. * app - Create project with a simple boilerplate, support typescript.
  44. * block - Create a umi block.
  45. * library - Create a library with umi.
  46. * plugin - Create a umi plugin.
  47. */
  48. const { type } = args;
  49. delete args.type;
  50. // 执行脚手架,开启项目构建程序, .lib/run.js => run
  51. run({
  52. name,
  53. type,
  54. args,
  55. });

.lib/run.js

  1. // 用于文件处理
  2. const fs = require('fs');
  3. // 用于系统路径,文件路径
  4. const path = require('path');
  5. // 输出不再单调,添加文字背景, 改变字体颜色 https://blog.csdn.net/qq_41153478/article/details/81505630
  6. const chalk = require('chalk');
  7. // 用于创建目录 https://www.cnblogs.com/xuepei/p/9429555.html
  8. const mkdirp = require('mkdirp');
  9. // 一个用户与命令行交互的工具, 用于窗口上选择 https://blog.csdn.net/qq_26733915/article/details/80461257
  10. const inquirer = require('inquirer');
  11. //是一款轻量级的实现复制文本到剪贴板功能的JavaScript插件。通过该插件可以将输入框,文本域,DIV元素中的文本等文本内容复制到剪贴板中
  12. const clipboardy = require('clipboardy');
  13. // 获取模版信息
  14. const generators = fs
  15. .readdirSync(`${__dirname}/generators`)
  16. .filter(f => !f.startsWith('.'))
  17. .map(f => {
  18. console.log('f', f);
  19. return {
  20. name: `${f.padEnd(15)} - ${chalk.gray(require(`./generators/${f}/meta.json`).description)}`,
  21. value: f,
  22. short: f,
  23. };
  24. });
  25. /**
  26. *
  27. * @param {*} generatorPath : 模版路径
  28. * @param {*} param1 :
  29. * name: 项目名称
  30. * cwd: process.cwd() 返回Node.js进程的当前工作目录。
  31. * args: process.argv的参数
  32. */
  33. const runGenerator = async (generatorPath, { name = '', cwd = process.cwd(), args = {} }) => {
  34. // 返回一个Promise, 用于按照模版生成项目
  35. return new Promise(resolve => {
  36. // 创建一个name变量的文件夹
  37. if (name) {
  38. mkdirp.sync(name);
  39. // 将node的运行环境路径切换到项目目录+name下
  40. cwd = path.join(cwd, name);
  41. }
  42. // 导入生成模版的命令 generatorPath模版对应的路径generatorPath/index.js
  43. const Generator = require(generatorPath);
  44. // 通过yeoman-generator 生成模版生成器 https://yeoman.io/authoring/
  45. const generator = new Generator({
  46. name,
  47. env: {
  48. cwd,
  49. },
  50. resolved: require.resolve(generatorPath),
  51. args,
  52. });
  53. /**
  54. * generator.run: 模版对应的路径,(例如:app/index.js)
  55. * 执行完执行callback回掉
  56. * 给用输出执行完成
  57. */
  58. return generator.run(() => {
  59. if (name) {
  60. if (process.platform !== `linux` || process.env.DISPLAY) {
  61. clipboardy.writeSync(`cd ${name}`);
  62. console.log('📋 Copied to clipboard, just use Ctrl+V');
  63. }
  64. }
  65. // 文件生成完成
  66. console.log('✨ File Generate Done');
  67. resolve(true);
  68. });
  69. });
  70. };
  71. /**
  72. * 主要的执行入口
  73. * @param {
  74. * name: 项目名称
  75. * type: 项目模版
  76. * args:命令行参数
  77. * } config
  78. *
  79. * process: node进程管理 http://nodejs.cn/api/process.html
  80. */
  81. const run = async config => {
  82. // process.send()方法将消息发送到父进程, 消息将会作为父进程的childProcess对象上的'message' 事件被接收。
  83. // 消息会进行序列化和解析。
  84. process.send && process.send({ type: 'prompt' });
  85. // 发送事件 messages, process 通过on去监听
  86. process.emit('message', { type: 'prompt' });
  87. let { type } = config;
  88. // 验证是否存在模版,如果没有则向用户发起询问
  89. if (!type) {
  90. // inquirer.prompt单选框,从generators选择
  91. const answers = await inquirer.prompt([
  92. {
  93. name: 'type',
  94. message: 'Select the boilerplate type',
  95. type: 'list',
  96. choices: generators,
  97. },
  98. ]);
  99. // answers用户的选择结果
  100. type = answers.type;
  101. }
  102. /**
  103. * 正式执行生成模版
  104. */
  105. try {
  106. return runGenerator(`./generators/${type}`, config);
  107. } catch(e) {
  108. console.error(chalk.red(`> Generate failed`), e);
  109. process.exit(1);
  110. }
  111. };
  112. module.exports = run;

app/index.js

  1. // debug以create-umi:generator
  2. const debug = require('debug')('create-umi:generator');
  3. // 获取基础Generator用于继承
  4. const BasicGenerator = require('../../BasicGenerator');
  5. class Generator extends BasicGenerator {
  6. prompting() {
  7. if (this.opts.args && 'isTypeScript' in this.opts.args && 'reactFeatures' in this.opts.args) {
  8. this.prompts = {
  9. isTypeScript: this.opts.args.isTypeScript,
  10. reactFeatures: this.opts.args.reactFeatures,
  11. };
  12. } else {
  13. const prompts = [
  14. {
  15. name: 'isTypeScript',
  16. type: 'confirm',
  17. message: 'Do you want to use typescript?',
  18. default: false,
  19. },
  20. {
  21. name: 'reactFeatures',
  22. message: 'What functionality do you want to enable?',
  23. type: 'checkbox',
  24. choices: [
  25. { name: 'antd', value: 'antd' },
  26. { name: 'dva', value: 'dva' },
  27. { name: 'code splitting', value: 'dynamicImport' },
  28. { name: 'dll', value: 'dll' },
  29. { name: 'internationalization', value: 'locale' },
  30. ],
  31. },
  32. ];
  33. return this.prompt(prompts).then(props => {
  34. this.prompts = props;
  35. });
  36. }
  37. }
  38. writing() {
  39. this.writeFiles({
  40. context: {
  41. name: this.name,
  42. ...this.prompts,
  43. },
  44. filterFiles: f => {
  45. const { isTypeScript, reactFeatures } = this.prompts;
  46. if (isTypeScript) {
  47. if (f.endsWith('.js')) return false;
  48. if (!reactFeatures.includes('dva')) {
  49. if (f.startsWith('src/models') || f === 'src/app.ts') return false;
  50. }
  51. if (!reactFeatures.includes('locale')) {
  52. if (f.startsWith('src/locales') || f.includes('umi-plugin-locale')) return false;
  53. }
  54. } else {
  55. if (this.isTsFile(f)) return false;
  56. if (!reactFeatures.includes('dva')) {
  57. if (f.startsWith('src/models') || f === 'src/app.js') return false;
  58. }
  59. if (!reactFeatures.includes('locale')) {
  60. if (f.startsWith('src/locales') || f.includes('umi-plugin-locale')) return false;
  61. }
  62. }
  63. return true;
  64. },
  65. });
  66. }
  67. }
  68. module.exports = Generator;

./lib/BasicGenerator.js

  1. // 脚手架生成器
  2. const Generator = require('yeoman-generator');
  3. // 在shell中使用正则去匹配文件,就好像stars,stuff
  4. const glob = require('glob');
  5. // 文件操作
  6. const { statSync } = require('fs');
  7. // path操作
  8. const { basename } = require('path');
  9. /**
  10. * 调试公开一个函数;只需将此函数作为模块的名称传递,
  11. * 它将返回经过修饰的console.error版本,以便您将调试语句传递给该模块。
  12. * 这将允许您切换模块不同部分以及整个模块的调试输出。
  13. * 所有的debug日志前面都会加上 create-umi:BasicGenerator
  14. */
  15. const debug = require('debug')('create-umi:BasicGenerator');
  16. function noop() {
  17. return true;
  18. }
  19. class BasicGenerator extends Generator {
  20. constructor(opts) {
  21. super(opts);
  22. // 初始化参数
  23. this.opts = opts;
  24. // 初始化名称
  25. this.name = basename(opts.env.cwd);
  26. }
  27. // 验证是否为Ts文件
  28. isTsFile(f) {
  29. return f.endsWith('.ts') || f.endsWith('.tsx') || !!/(tsconfig\.json|tslint\.yml)/g.test(f);
  30. }
  31. /**
  32. *
  33. * To Do 写文件
  34. * 知识点:
  35. * 1. this.templatePath(): templatePath(...path: string[]): string; // 获取当前templates的地址
  36. *
  37. * 2. glob.sync(pattern, [options])
  38. * - pattern {String} Pattern to be matched
  39. * - options {Object}
  40. * return: {Array<String>} filenames found matching the pattern
  41. *
  42. * 3. this.fs.copyTpl: https://haztivity.github.io/generator-haztivity/interfaces/generatorhaztivity.scogenerator.base.memfseditor.html#copytpl
  43. * fs: Generator.MemFsEditor;
  44. * copyTpl(
  45. * from: string,
  46. * to: string,
  47. * context: __type,
  48. * templateOptions?: __type,
  49. * copyOptions?: __type): void
  50. */
  51. writeFiles({ context, filterFiles = noop }) {
  52. // We have multiple welcome file, random this
  53. // 获取 templates 里面符合此“**/assets/welcomeImgs/*”条件下的所有文件
  54. /**
  55. * 根据用户的回答依次执行文件copy操作
  56. * filterFiles: 过滤条件
  57. */
  58. const welcomeImages = glob
  59. .sync('**/assets/welcomeImgs/*', {
  60. cwd: this.templatePath(),
  61. dot: true, // 包括dot文件
  62. })
  63. .filter(filterFiles);
  64. if (welcomeImages.length) {
  65. const welcomeImg = welcomeImages[Math.floor(Math.random() * welcomeImages.length)];
  66. debug(`copy ${welcomeImg}`);
  67. // fs: Generator.MemFsEditor;
  68. this.fs.copyTpl(
  69. this.templatePath(welcomeImg),
  70. this.destinationPath(welcomeImg.replace(/welcomeImgs.*$/, 'yay.jpg')),
  71. context,
  72. );
  73. }
  74. debug(`context: ${JSON.stringify(context)}`);
  75. /**
  76. * 匹配所有文件
  77. * 不包含welcomeImgs
  78. * 一次copy文件到指定文件夹
  79. */
  80. glob
  81. .sync('**/*', {
  82. cwd: this.templatePath(),
  83. dot: true,
  84. })
  85. .filter(filterFiles)
  86. .filter(file => !file.includes('welcomeImgs'))
  87. .forEach(file => {
  88. debug(`copy ${file}`);
  89. const filePath = this.templatePath(file);
  90. if (statSync(filePath).isFile()) {
  91. this.fs.copyTpl(
  92. this.templatePath(filePath),
  93. this.destinationPath(file.replace(/^_/, '.')),
  94. context,
  95. );
  96. }
  97. });
  98. }
  99. /**
  100. * 源码
  101. * Generator: prompt<A extends Generator.Answers = Generator.Answers>(questions: Generator.Questions<A>): Promise<A>;
  102. * 发起questions得到相应的回答
  103. *
  104. */
  105. prompt(questions) {
  106. process.send && process.send({ type: 'prompt' });
  107. process.emit('message', { type: 'prompt' });
  108. /**
  109. * 发起question
  110. */
  111. return super.prompt(questions);
  112. }
  113. }
  114. module.exports = BasicGenerator;

关联的工具包整理

  1. npm的publish工具 np: https://github.com/sindresorhus/np#readme
  2. 代码格式化工具: prettier
  3. egg-bin:服务工具
  4. coffee: 测试工具node.js (Test command line on Node.js)
  5. mm:(简单的mock.js工具包) An simple but flexible mock(or say stub) package, mock mate.
  6. chalk: Terminal string styling done right (控制台文本样式正确输出)
  7. clipboardy: Access the system clipboard (copy/paste) 访问系统剪贴板(复制/粘贴)
  8. debug: A tiny JavaScript debugging utility modelled after Node.js core’s debugging technique. Works in Node.js and web browsers.(一个模仿Node.js核心调试技术的微型JavaScript调试实用程序。可在Node.js和Web浏览器中使用)
  9. execa: Process execution for humans (为开发者提供执行程序流程的控制)
  10. fs-extra: fs-extra adds file system methods that aren’t included in the native fs module and adds promise support to the fs methods. It also uses graceful-fs to prevent EMFILE errors. It should be a drop in replacement for fs.(fs-extra添加了本机fs模块未包含的文件系统方法,并为fs方法添加了promise支持。它还使用graceful -fs防止EMFILE错误。应该是替换fs的下降。)
  11. glob: Match files using the patterns the shell uses, like stars and stuff.(在shell中使用正则去匹配文件,就好像stars,stuff)
  12. inquirer: A collection of common interactive command line user interfaces.常见的交互式命令行用户界面的集合。
  13. mkdirp: Like mkdir -p, but in node.js!(像mkdir -p/在某目录下创建子目录,但是是在node环境使用)
  14. prettier: Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.(prettier 一个代码格式化工具, 它通过解析代码并使用自己的规则(考虑最大行长)重新打印代码,从而实现一致的样式,并在必要时包装代码。)
  15. semver: As a node module, npm的语义话版本,是node的module
  16. sort-package-json: Pass it a JSON string, it’ll return a new JSON string, sorted by the keys typically found in a package.json,Pass it an object, it’ll return an object sorted by the keys typically found in a package.json(向其传递一个JSON字符串,它将返回一个新的JSON字符串,该字符串按照通常在package.json中找到的键进行排序向其传递一个对象,它将返回一个对象,该对象按通常在package.json中找到的键排序)
  17. sylvanas: A tool to convert TypeScript to JavaScript with human-like code style.(开发者热爱的代码格式工具用于将typescript转化为javascript版本)
  18. umi-utils: sorrycc开发的umi工具
  19. yargs-parser: The mighty option parser used by yargs.(通过yargs使用强大的选项解析器。)
  20. yeoman-generator: Rails-inspired generator system that provides scaffolding for your apps(受Rails启发的生成器系统,可为您的应用程序提供脚手架)

附加工具包

yargs: Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface.(Yargs通过解析参数并生成优雅的用户界面来帮助您构建交互式命令行工具。)

感言

代码还是比较简单,需要对node的运行环境熟悉,对yeoman-genarator的模版生成要熟悉,看源码的感觉会提高自己的思维层次。 1月前的目标终于完成了, 后面自己也会去写一些简单的脚手架,顺便给大家分一下typescript的文档生成typeDOC。 一起加油! 小伙伴们,后面会为大家分享antd-design的源码,如果我的文章对你有帮助可以给我送一个🌾吗?。