已生成app模版为例,其他同理
./cli.js ( 脚本文件 )
#!/usr/bin/env node// 命名行解析,获取参数const yParser = require('yargs-parser');const semver = require('semver');// 文件管理const { existsSync } = require('fs');// 路径管理const { join } = require('path');// 控制台内容颜色控制const chalk = require('chalk');const run = require('./lib/run');// print version and @local/*** process.argv: 返回一个数组,其中包含当启动 Node.js 进程时传入的命令行参数* 第一个元素是 process.execPath* 第二个元素将是正在执行的 JavaScript 文件的路径。* 其余元素将是任何其他命令行参数。* node cli.js umi-project* ["/usr/local/bin/node", "/Users/wangyangyang/Downloads/code/demo/create-umi…", "umi-project"]*/const args = yParser(process.argv.slice(2));if (args.v || args.version) {console.log(require('./package').version);if (existsSync(join(__dirname, '.local'))) {console.log(chalk.cyan('@local'));}process.exit(0);}/*** semver: 对npm包的版本管理,比较, 规范等等解析* https://cnodejs.org/topic/570f8331510629637266685a*/if (!semver.satisfies(process.version, '>= 8.0.0')) {console.error(chalk.red('✘ The generator will only work with Node v8.0.0 and up!'));process.exit(1);}// 获取传入的项目名称const name = args._[0] || '';// 根据run文件得知,type设置项目的样板/*** 目前umi包含5种代码样板* ant-design-pro - Create project with a layout-only ant-design-pro boilerplate, use together with umi block.* app - Create project with a simple boilerplate, support typescript.* block - Create a umi block.* library - Create a library with umi.* plugin - Create a umi plugin.*/const { type } = args;delete args.type;// 执行脚手架,开启项目构建程序, .lib/run.js => runrun({name,type,args,});
.lib/run.js
// 用于文件处理const fs = require('fs');// 用于系统路径,文件路径const path = require('path');// 输出不再单调,添加文字背景, 改变字体颜色 https://blog.csdn.net/qq_41153478/article/details/81505630const chalk = require('chalk');// 用于创建目录 https://www.cnblogs.com/xuepei/p/9429555.htmlconst mkdirp = require('mkdirp');// 一个用户与命令行交互的工具, 用于窗口上选择 https://blog.csdn.net/qq_26733915/article/details/80461257const inquirer = require('inquirer');//是一款轻量级的实现复制文本到剪贴板功能的JavaScript插件。通过该插件可以将输入框,文本域,DIV元素中的文本等文本内容复制到剪贴板中const clipboardy = require('clipboardy');// 获取模版信息const generators = fs.readdirSync(`${__dirname}/generators`).filter(f => !f.startsWith('.')).map(f => {console.log('f', f);return {name: `${f.padEnd(15)} - ${chalk.gray(require(`./generators/${f}/meta.json`).description)}`,value: f,short: f,};});/**** @param {*} generatorPath : 模版路径* @param {*} param1 :* name: 项目名称* cwd: process.cwd() 返回Node.js进程的当前工作目录。* args: process.argv的参数*/const runGenerator = async (generatorPath, { name = '', cwd = process.cwd(), args = {} }) => {// 返回一个Promise, 用于按照模版生成项目return new Promise(resolve => {// 创建一个name变量的文件夹if (name) {mkdirp.sync(name);// 将node的运行环境路径切换到项目目录+name下cwd = path.join(cwd, name);}// 导入生成模版的命令 generatorPath模版对应的路径generatorPath/index.jsconst Generator = require(generatorPath);// 通过yeoman-generator 生成模版生成器 https://yeoman.io/authoring/const generator = new Generator({name,env: {cwd,},resolved: require.resolve(generatorPath),args,});/*** generator.run: 模版对应的路径,(例如:app/index.js)* 执行完执行callback回掉* 给用输出执行完成*/return generator.run(() => {if (name) {if (process.platform !== `linux` || process.env.DISPLAY) {clipboardy.writeSync(`cd ${name}`);console.log('📋 Copied to clipboard, just use Ctrl+V');}}// 文件生成完成console.log('✨ File Generate Done');resolve(true);});});};/*** 主要的执行入口* @param {* name: 项目名称* type: 项目模版* args:命令行参数* } config** process: node进程管理 http://nodejs.cn/api/process.html*/const run = async config => {// process.send()方法将消息发送到父进程, 消息将会作为父进程的childProcess对象上的'message' 事件被接收。// 消息会进行序列化和解析。process.send && process.send({ type: 'prompt' });// 发送事件 messages, process 通过on去监听process.emit('message', { type: 'prompt' });let { type } = config;// 验证是否存在模版,如果没有则向用户发起询问if (!type) {// inquirer.prompt单选框,从generators选择const answers = await inquirer.prompt([{name: 'type',message: 'Select the boilerplate type',type: 'list',choices: generators,},]);// answers用户的选择结果type = answers.type;}/*** 正式执行生成模版*/try {return runGenerator(`./generators/${type}`, config);} catch(e) {console.error(chalk.red(`> Generate failed`), e);process.exit(1);}};module.exports = run;
app/index.js
// debug以create-umi:generatorconst debug = require('debug')('create-umi:generator');// 获取基础Generator用于继承const BasicGenerator = require('../../BasicGenerator');class Generator extends BasicGenerator {prompting() {if (this.opts.args && 'isTypeScript' in this.opts.args && 'reactFeatures' in this.opts.args) {this.prompts = {isTypeScript: this.opts.args.isTypeScript,reactFeatures: this.opts.args.reactFeatures,};} else {const prompts = [{name: 'isTypeScript',type: 'confirm',message: 'Do you want to use typescript?',default: false,},{name: 'reactFeatures',message: 'What functionality do you want to enable?',type: 'checkbox',choices: [{ name: 'antd', value: 'antd' },{ name: 'dva', value: 'dva' },{ name: 'code splitting', value: 'dynamicImport' },{ name: 'dll', value: 'dll' },{ name: 'internationalization', value: 'locale' },],},];return this.prompt(prompts).then(props => {this.prompts = props;});}}writing() {this.writeFiles({context: {name: this.name,...this.prompts,},filterFiles: f => {const { isTypeScript, reactFeatures } = this.prompts;if (isTypeScript) {if (f.endsWith('.js')) return false;if (!reactFeatures.includes('dva')) {if (f.startsWith('src/models') || f === 'src/app.ts') return false;}if (!reactFeatures.includes('locale')) {if (f.startsWith('src/locales') || f.includes('umi-plugin-locale')) return false;}} else {if (this.isTsFile(f)) return false;if (!reactFeatures.includes('dva')) {if (f.startsWith('src/models') || f === 'src/app.js') return false;}if (!reactFeatures.includes('locale')) {if (f.startsWith('src/locales') || f.includes('umi-plugin-locale')) return false;}}return true;},});}}module.exports = Generator;
./lib/BasicGenerator.js
// 脚手架生成器const Generator = require('yeoman-generator');// 在shell中使用正则去匹配文件,就好像stars,stuffconst glob = require('glob');// 文件操作const { statSync } = require('fs');// path操作const { basename } = require('path');/*** 调试公开一个函数;只需将此函数作为模块的名称传递,* 它将返回经过修饰的console.error版本,以便您将调试语句传递给该模块。* 这将允许您切换模块不同部分以及整个模块的调试输出。* 所有的debug日志前面都会加上 create-umi:BasicGenerator*/const debug = require('debug')('create-umi:BasicGenerator');function noop() {return true;}class BasicGenerator extends Generator {constructor(opts) {super(opts);// 初始化参数this.opts = opts;// 初始化名称this.name = basename(opts.env.cwd);}// 验证是否为Ts文件isTsFile(f) {return f.endsWith('.ts') || f.endsWith('.tsx') || !!/(tsconfig\.json|tslint\.yml)/g.test(f);}/**** To Do 写文件* 知识点:* 1. this.templatePath(): templatePath(...path: string[]): string; // 获取当前templates的地址** 2. glob.sync(pattern, [options])* - pattern {String} Pattern to be matched* - options {Object}* return: {Array<String>} filenames found matching the pattern** 3. this.fs.copyTpl: https://haztivity.github.io/generator-haztivity/interfaces/generatorhaztivity.scogenerator.base.memfseditor.html#copytpl* fs: Generator.MemFsEditor;* copyTpl(* from: string,* to: string,* context: __type,* templateOptions?: __type,* copyOptions?: __type): void*/writeFiles({ context, filterFiles = noop }) {// We have multiple welcome file, random this// 获取 templates 里面符合此“**/assets/welcomeImgs/*”条件下的所有文件/*** 根据用户的回答依次执行文件copy操作* filterFiles: 过滤条件*/const welcomeImages = glob.sync('**/assets/welcomeImgs/*', {cwd: this.templatePath(),dot: true, // 包括dot文件}).filter(filterFiles);if (welcomeImages.length) {const welcomeImg = welcomeImages[Math.floor(Math.random() * welcomeImages.length)];debug(`copy ${welcomeImg}`);// fs: Generator.MemFsEditor;this.fs.copyTpl(this.templatePath(welcomeImg),this.destinationPath(welcomeImg.replace(/welcomeImgs.*$/, 'yay.jpg')),context,);}debug(`context: ${JSON.stringify(context)}`);/*** 匹配所有文件* 不包含welcomeImgs* 一次copy文件到指定文件夹*/glob.sync('**/*', {cwd: this.templatePath(),dot: true,}).filter(filterFiles).filter(file => !file.includes('welcomeImgs')).forEach(file => {debug(`copy ${file}`);const filePath = this.templatePath(file);if (statSync(filePath).isFile()) {this.fs.copyTpl(this.templatePath(filePath),this.destinationPath(file.replace(/^_/, '.')),context,);}});}/*** 源码* Generator: prompt<A extends Generator.Answers = Generator.Answers>(questions: Generator.Questions<A>): Promise<A>;* 发起questions得到相应的回答**/prompt(questions) {process.send && process.send({ type: 'prompt' });process.emit('message', { type: 'prompt' });/*** 发起question*/return super.prompt(questions);}}module.exports = BasicGenerator;
关联的工具包整理
- npm的publish工具 np: https://github.com/sindresorhus/np#readme
- 代码格式化工具: prettier
- egg-bin:服务工具
- coffee: 测试工具node.js (Test command line on Node.js)
- mm:(简单的mock.js工具包) An simple but flexible mock(or say stub) package, mock mate.
- chalk: Terminal string styling done right (控制台文本样式正确输出)
- clipboardy: Access the system clipboard (copy/paste) 访问系统剪贴板(复制/粘贴)
- 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浏览器中使用)
- execa: Process execution for humans (为开发者提供执行程序流程的控制)
- fs-extra:
fs-extraadds file system methods that aren’t included in the nativefsmodule and adds promise support to thefsmethods. It also usesgraceful-fsto preventEMFILEerrors. It should be a drop in replacement forfs.(fs-extra添加了本机fs模块未包含的文件系统方法,并为fs方法添加了promise支持。它还使用graceful -fs防止EMFILE错误。应该是替换fs的下降。) - glob: Match files using the patterns the shell uses, like stars and stuff.(在shell中使用正则去匹配文件,就好像stars,stuff)
- inquirer: A collection of common interactive command line user interfaces.常见的交互式命令行用户界面的集合。
- mkdirp: Like
mkdir -p, but in node.js!(像mkdir -p/在某目录下创建子目录,但是是在node环境使用) - 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 一个代码格式化工具, 它通过解析代码并使用自己的规则(考虑最大行长)重新打印代码,从而实现一致的样式,并在必要时包装代码。)
- semver: As a node module, npm的语义话版本,是node的module
- 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中找到的键排序)
- sylvanas: A tool to convert TypeScript to JavaScript with human-like code style.(开发者热爱的代码格式工具用于将typescript转化为javascript版本)
- umi-utils: sorrycc开发的umi工具
- yargs-parser: The mighty option parser used by yargs.(通过yargs使用强大的选项解析器。)
- 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的源码,如果我的文章对你有帮助可以给我送一个🌾吗?。
