TypeScript 组件脚手架
创建 .tsx 组件、index.ts 导出和可选的 props 占位代码。
React 组件生成器
批量生成 JavaScript 或 TypeScript React 组件目录及对应的入口文件, 可选择 CSS Modules 或 SCSS Modules,并支持项目默认配置、自定义模板、 测试文件和项目感知的 Prettier 格式化。
$ create-new-react-component
? What are the names of your components? ProductCard UserCard
? What type of component would you like to create?
Arrow Function
? What language would you like to use? ts
? What styling solution would you like to use? scss
ProductCard/
index.ts
ProductCard.tsx
ProductCard.module.scss
ProductCard.test.tsx
UserCard/
index.ts
UserCard.tsx
UserCard.module.scss
UserCard.test.tsx
安装
CLI 可以从交互式提示开始,校验 PascalCase 组件名称, 然后在当前工作目录或指定目录中写入组件文件夹。
npx create-new-react-component Button UserCard Modal
create-new-react-component Button UserCard --lang ts --style scss --with-test --format
使用场景
当你需要可重复的组件目录输出,又不想引入完整应用框架、构建工具或设计系统依赖时,
可以使用 create-new-react-component。
创建 .tsx 组件、index.ts 导出和可选的 props 占位代码。
生成同级 Module 文件,或使用 --style none 创建无样式组件。
使用 .cnrc.json 统一语言、样式、测试和目录默认值。
通过 --template 将可复用模板文件加入交互式选择列表。
使用一组选项创建多个组件,并在写入前完成全有或全无的校验。
在组件旁添加 Component.test.jsx 或 Component.test.tsx。
CLI 参数
非交互式默认值为 functional、js 和 css。
命令行参数优先于 .cnrc.json,配置值优先于内置默认值。
--lang js|ts选择 JavaScript 或 TypeScript 组件文件。
--style css|scss|none生成 CSS Modules、SCSS Modules,或不生成样式文件。
--type使用 functional、arrow、class、memoized 或 forwardRef 模板。
--dir在目标目录下创建组件文件夹。
--with-test添加基础的同级组件测试文件。
--format使用最近的 Prettier 配置格式化生成文件。
模板
经典的具名函数组件,可选择生成 props。
简洁的 const Component = () => {} 输出。
适用于旧项目的 React class 组件脚手架。
使用 React.memo 包装组件,保持稳定的渲染路径。
创建可将 ref 传递给 DOM 节点的组件。
加载自己的可复用模板文件或模板目录。
ComponentName/
+-- index.js | index.ts
+-- ComponentName.jsx | ComponentName.tsx
+-- ComponentName.module.css | .scss
`-- ComponentName.test.jsx | .tsx
为什么选择它
这个 CLI 适合已有 React 项目、只需要快速建立可预测组件目录约定的团队。 它不会引入框架设置,生成内容保持易读,并让每个项目自行决定样式、测试和模板规范。
create-new-react-component UserCard ProductCard \
--type forwardRef \
--lang ts \
--style scss \
--with-props \
--with-test \
--format \
--dir src/components
常见问题
运行 npx create-new-react-component Button,
即可创建包含组件文件和入口导出的 Button 目录。
可以。使用 --lang ts 生成 .tsx 组件文件和
index.ts 导出文件。
支持。使用 --style css、--style scss 或
--style none 控制生成的样式文件。
可以。传入 create-new-react-component Button UserCard Modal
等多个名称。CLI 会在写入文件前验证整个批次。
可以。添加 --format,或在 .cnrc.json 中设置
"format": true,即可使用最近的项目配置。
可以。添加 --with-test 可生成同级的
Component.test.jsx 或 Component.test.tsx 文件。
可以。添加 .cnrc.json 文件,为语言、样式、组件类型、
测试生成和基础目录等选项设置默认值。
可以。使用 --template 指定单个模板文件,或使用
--template-dir 指定可复用模板目录。