在项目中的最好的提效方案就是复用,比如将常用模块封装,给到其他页面复用,就是我们经常提到的组件(复制使用的情况)。将项目中的方案进行封装,给到不同的项目中使用,就是我们说到的脚手架。而这些好的组件或者脚手架,要快速的被其他人员使用,就要用到生成器。简单的理解就是使用脚本帮你复制了一份,像很多项目中经常会执行的新建项目就是生成器的一种能力体现。
npx create-xxx appName
Umi 中将生成器的目标定的更加细化,不是提供一整个脚手架,而是提供脚手架中的某一个方案,所以取名微生成器,其实灵感来源是 modern.js 的微生成器。
Umi 的微生成器有统一的命令入口调用:
umi generate (alias: umi g) [type]
内置微生成器列表
页面生成器
比如快速生成一个初始的简单页面,可以使用一下方法方式。
交互式输入页面名称和文件生成方式:
$ umi g page
? What is the name of page? › mypage
? How dou you want page files to be created? › - Use arrow-keys. Return to submit.
❯ mypage/index.{tsx,less}mypage.{tsx,less}
或者直接指明页面名称直接生成:
$ umi g page foo
Write: src/pages/foo.tsx
Write: src/pages/foo.less
如果你的项目风格是使用目录方式,比如基于 Umi 构建的前端框架 alita 中,就只有目录下的 index 文件才会被识别成路由,所以就可以采用以目录方式生成页面,目录下为页面的组件和样式文件:
$ umi g page bar --dir
Write: src/pages/bar/index.less
Write: src/pages/bar/index.tsx
批量生成多个页面:
$ umi g pagepage1page2 a/nested/page3
info- @local
Write: src/pages/page1.tsx
Write: src/pages/page1.less
Write: src/pages/page2.tsx
Write: src/pages/page2.less
Write: src/pages/a/nested/page3.tsx
Write: src/pages/a/nested/page3.less
剩余内置微生成器清单
后续我们会在介绍每一个能力的时候,使用到对应的微生成器。
组件生成器
在 src/components/
目录下生成项目需要的组件。和页面生成器一样,组件生成器也有多种生成方式。
交互式生成:
$ umi g component
info- @local
✔ Please input you component Name … foo
Write: src/components/Foo/index.ts
Write: src/components/Foo/Foo.tsx
直接生成:
$ umi g component bar
info- @local
Write: src/components/Bar/index.ts
Write: src/components/Bar/Bar.tsx
嵌套生成:
<